@tahanabavi/typefetch 1.5.6 → 1.6.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/index.mjs CHANGED
@@ -1,13 +1,17 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
1
5
  // src/client.ts
2
6
  import { z } from "zod";
3
7
  var RichError = class extends Error {
4
- status;
5
- code;
6
- title;
7
- detail;
8
- errors;
9
8
  constructor(error) {
10
9
  super(error.message);
10
+ __publicField(this, "status");
11
+ __publicField(this, "code");
12
+ __publicField(this, "title");
13
+ __publicField(this, "detail");
14
+ __publicField(this, "errors");
11
15
  Object.assign(this, error);
12
16
  }
13
17
  };
@@ -20,23 +24,21 @@ var REQUEST_PART_KEYS = /* @__PURE__ */ new Set([
20
24
  ]);
21
25
  var ApiClient = class {
22
26
  constructor(config, contracts) {
23
- this.config = config;
24
- this.contracts = contracts;
27
+ __publicField(this, "config", config);
28
+ __publicField(this, "contracts", contracts);
29
+ __publicField(this, "middlewares", []);
30
+ __publicField(this, "errorHandler");
31
+ __publicField(this, "responseTransform", (d) => d);
32
+ __publicField(this, "useMockData", false);
33
+ __publicField(this, "mockDelay", { min: 100, max: 1e3 });
34
+ __publicField(this, "responseWrapper");
35
+ __publicField(this, "tokenProvider");
36
+ __publicField(this, "retryConfig");
37
+ __publicField(this, "_modules");
25
38
  this.useMockData = config.useMockData || false;
26
39
  this.mockDelay = config.mockDelay || { min: 100, max: 1e3 };
27
40
  this.tokenProvider = config.tokenProvider;
28
41
  }
29
- config;
30
- contracts;
31
- middlewares = [];
32
- errorHandler;
33
- responseTransform = (d) => d;
34
- useMockData = false;
35
- mockDelay = { min: 100, max: 1e3 };
36
- responseWrapper;
37
- tokenProvider;
38
- retryConfig;
39
- _modules;
40
42
  init() {
41
43
  const modules = {};
42
44
  for (const moduleName in this.contracts) {
@@ -265,17 +267,22 @@ var ApiClient = class {
265
267
  isObjectRecord(value) {
266
268
  return typeof value === "object" && value !== null && !Array.isArray(value);
267
269
  }
268
- applyPathParams(url, pathParams) {
269
- return url.replace(/:([A-Za-z0-9_]+)/g, (_, key) => {
270
- const value = pathParams?.[key];
271
- if (value === void 0 || value === null) {
272
- throw this.createError({
273
- message: `Missing path param "${key}"`,
274
- code: "MISSING_PATH_PARAM"
275
- });
270
+ applyPathParams(fullUrl, pathParams) {
271
+ const url = new URL(fullUrl);
272
+ const replacedPathname = url.pathname.replace(
273
+ /:([A-Za-z0-9_]+)/g,
274
+ (_, key) => {
275
+ const value = pathParams?.[key];
276
+ if (value === void 0 || value === null) {
277
+ throw this.createError({
278
+ message: `Missing path param "${key}"`,
279
+ code: "MISSING_PATH_PARAM"
280
+ });
281
+ }
282
+ return encodeURIComponent(String(value));
276
283
  }
277
- return encodeURIComponent(String(value));
278
- });
284
+ );
285
+ return `${url.origin}${replacedPathname}${url.search}${url.hash}`;
279
286
  }
280
287
  appendQueryParams(url, query) {
281
288
  if (!query) return url;
@@ -691,12 +698,698 @@ var makeRequestSchema = () => (defs = {}) => {
691
698
  headers: headersSchema
692
699
  });
693
700
  };
701
+
702
+ // src/modules/tester/context.ts
703
+ var TypeFetchTestContext = class {
704
+ constructor(initialData = {}) {
705
+ __publicField(this, "data");
706
+ this.data = { ...initialData };
707
+ }
708
+ get(key) {
709
+ return this.data[key];
710
+ }
711
+ set(key, value) {
712
+ this.data[key] = value;
713
+ }
714
+ has(key) {
715
+ return Object.prototype.hasOwnProperty.call(this.data, key);
716
+ }
717
+ };
718
+
719
+ // src/modules/tester/generate-input.ts
720
+ var DEFAULT_MAX_DEPTH = 5;
721
+ function generateInput(schema, options = {}) {
722
+ return generateValue(schema, options, [], 0);
723
+ }
724
+ function generateValue(schema, options, path, depth) {
725
+ const override = resolveOverride(options, path);
726
+ if (override.exists) return override.value;
727
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
728
+ if (depth > maxDepth) return null;
729
+ const kind = getKind(schema);
730
+ const def = getDef(schema);
731
+ switch (kind) {
732
+ case "optional":
733
+ if (options.includeOptional === false) return void 0;
734
+ return generateValue(getInnerType(schema, def), options, path, depth + 1);
735
+ case "nullable":
736
+ return generateValue(getInnerType(schema, def), options, path, depth + 1);
737
+ case "default":
738
+ return getDefaultValue(def) ?? generateValue(getInnerType(schema, def), options, path, depth + 1);
739
+ case "catch":
740
+ case "readonly":
741
+ case "branded":
742
+ case "promise":
743
+ return generateValue(getInnerType(schema, def), options, path, depth + 1);
744
+ case "effects":
745
+ case "pipeline":
746
+ case "pipe":
747
+ return generateValue(
748
+ def.schema ?? def.in ?? def.out,
749
+ options,
750
+ path,
751
+ depth + 1
752
+ );
753
+ case "object":
754
+ return generateObject(schema, options, path, depth);
755
+ case "array": {
756
+ if (options.includeArrayItems === false) return [];
757
+ const itemSchema = def.type ?? def.element ?? def.innerType;
758
+ return itemSchema ? [generateValue(itemSchema, options, path.concat("0"), depth + 1)] : [];
759
+ }
760
+ case "tuple": {
761
+ const items = def.items ?? [];
762
+ return items.map(
763
+ (item, index) => generateValue(item, options, path.concat(String(index)), depth + 1)
764
+ );
765
+ }
766
+ case "record": {
767
+ const valueType = def.valueType ?? def.valueSchema ?? def.value;
768
+ return {
769
+ key: valueType ? generateValue(valueType, options, path.concat("key"), depth + 1) : "value"
770
+ };
771
+ }
772
+ case "union": {
773
+ const optionsList = def.options ?? [];
774
+ return optionsList.length ? generateValue(optionsList[0], options, path, depth + 1) : null;
775
+ }
776
+ case "discriminatedunion":
777
+ case "discriminated_union": {
778
+ const optionsMap = def.optionsMap;
779
+ const first = optionsMap?.values().next().value ?? def.options?.[0];
780
+ return first ? generateValue(first, options, path, depth + 1) : null;
781
+ }
782
+ case "intersection": {
783
+ const left = generateValue(def.left, options, path, depth + 1);
784
+ const right = generateValue(def.right, options, path, depth + 1);
785
+ if (isObject(left) && isObject(right)) return { ...left, ...right };
786
+ return right ?? left;
787
+ }
788
+ case "literal": {
789
+ const values = def.values ?? ("value" in def ? [def.value] : void 0);
790
+ return Array.isArray(values) ? values[0] : values?.values?.().next?.().value;
791
+ }
792
+ case "enum":
793
+ case "nativeenum":
794
+ case "native_enum": {
795
+ const values = getEnumValues(schema, def);
796
+ return values[0] ?? "value";
797
+ }
798
+ case "string":
799
+ return generateString(path, def, options);
800
+ case "number":
801
+ return generateNumber(def);
802
+ case "bigint":
803
+ return BigInt(1);
804
+ case "boolean":
805
+ return true;
806
+ case "date":
807
+ return /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z");
808
+ case "null":
809
+ return null;
810
+ case "undefined":
811
+ case "void":
812
+ return void 0;
813
+ case "nan":
814
+ return Number.NaN;
815
+ case "any":
816
+ case "unknown":
817
+ return guessByPath(path, options);
818
+ case "never":
819
+ throw new Error(
820
+ `Cannot generate input for never schema at ${path.join(".") || "root"}`
821
+ );
822
+ default:
823
+ return guessByPath(path, options);
824
+ }
825
+ }
826
+ function generateObject(schema, options, path, depth) {
827
+ const shape = getShape(schema);
828
+ const output = {};
829
+ for (const [key, childSchema] of Object.entries(shape)) {
830
+ const value = generateValue(
831
+ childSchema,
832
+ options,
833
+ path.concat(key),
834
+ depth + 1
835
+ );
836
+ if (value !== void 0 || options.includeOptional !== false)
837
+ output[key] = value;
838
+ }
839
+ return output;
840
+ }
841
+ function generateString(path, def, options) {
842
+ const key = path[path.length - 1]?.toLowerCase() ?? "";
843
+ const fullPath = path.join(".").toLowerCase();
844
+ const minLength = getStringMinLength(def);
845
+ const ensureMinLength = (value) => minLength && value.length < minLength ? value.padEnd(minLength, "x") : value;
846
+ if (isFileField(key, fullPath))
847
+ return options.fileFactory?.() ?? defaultFileValue();
848
+ if (key.includes("email")) {
849
+ const base = "test@example.com";
850
+ if (!minLength || base.length >= minLength) return base;
851
+ return `test${"x".repeat(minLength - base.length)}@example.com`;
852
+ }
853
+ if (key.includes("url") || key.includes("website")) {
854
+ const base = "https://example.com";
855
+ if (!minLength || base.length >= minLength) return base;
856
+ return `${base}/${"x".repeat(minLength - base.length)}`;
857
+ }
858
+ if (key === "uuid" || key.endsWith("uuid")) {
859
+ return "550e8400-e29b-41d4-a716-446655440000";
860
+ }
861
+ if (key === "id" || key.endsWith("id") || fullPath.endsWith(".path.id")) {
862
+ return ensureMinLength("1");
863
+ }
864
+ if (key.includes("phone")) return ensureMinLength("+10000000000");
865
+ if (key.includes("name")) return ensureMinLength("Test Name");
866
+ if (key.includes("password")) return ensureMinLength("StrongPass123!");
867
+ if (key.includes("token")) return ensureMinLength("test-token");
868
+ return ensureMinLength("test-string");
869
+ }
870
+ function generateNumber(def) {
871
+ const min = getNumberMin(def);
872
+ if (typeof min === "number") return min;
873
+ return 1;
874
+ }
875
+ function guessByPath(path, options) {
876
+ const key = path[path.length - 1]?.toLowerCase() ?? "";
877
+ const fullPath = path.join(".").toLowerCase();
878
+ if (isFileField(key, fullPath))
879
+ return options.fileFactory?.() ?? defaultFileValue();
880
+ if (key.includes("count") || key.includes("page") || key.includes("limit"))
881
+ return 1;
882
+ if (key.startsWith("is") || key.startsWith("has") || key.includes("active"))
883
+ return true;
884
+ return "test-value";
885
+ }
886
+ function resolveOverride(options, path) {
887
+ const values = options.values ?? {};
888
+ const candidates = [
889
+ path.join("."),
890
+ path.slice(-2).join("."),
891
+ path[path.length - 1] ?? ""
892
+ ];
893
+ for (const key of candidates) {
894
+ if (key && Object.prototype.hasOwnProperty.call(values, key)) {
895
+ const raw = values[key];
896
+ return {
897
+ exists: true,
898
+ value: typeof raw === "function" ? raw(path.join(".")) : raw
899
+ };
900
+ }
901
+ }
902
+ return { exists: false, value: void 0 };
903
+ }
904
+ function getDef(schema) {
905
+ return schema._def ?? schema.def ?? {};
906
+ }
907
+ function getKind(schema) {
908
+ const def = getDef(schema);
909
+ const raw = def.typeName ?? def.type ?? schema.constructor?.name ?? "unknown";
910
+ return String(raw).replace(/^Zod/, "").replace(/-/g, "_").toLowerCase();
911
+ }
912
+ function getInnerType(schema, def = getDef(schema)) {
913
+ return schema.unwrap?.() ?? def.innerType ?? def.schema ?? def.type;
914
+ }
915
+ function getShape(schema) {
916
+ const def = getDef(schema);
917
+ const shape = schema.shape ?? def.shape;
918
+ return typeof shape === "function" ? shape() : shape ?? {};
919
+ }
920
+ function getDefaultValue(def) {
921
+ const value = def.defaultValue;
922
+ return typeof value === "function" ? value() : value;
923
+ }
924
+ function getEnumValues(schema, def) {
925
+ if (Array.isArray(schema.options)) return schema.options;
926
+ if (Array.isArray(def.values)) return def.values;
927
+ if (def.entries && typeof def.entries === "object")
928
+ return Object.values(def.entries);
929
+ if (def.values && typeof def.values === "object")
930
+ return Object.values(def.values);
931
+ return [];
932
+ }
933
+ function getStringMinLength(def) {
934
+ for (const check of def.checks ?? []) {
935
+ const c = check?._zod?.def ?? check;
936
+ if ((c.kind === "min" || c.check === "min_length" || c.type === "min") && typeof c.value === "number")
937
+ return c.value;
938
+ if (typeof c.minimum === "number") return c.minimum;
939
+ }
940
+ return void 0;
941
+ }
942
+ function getNumberMin(def) {
943
+ for (const check of def.checks ?? []) {
944
+ const c = check?._zod?.def ?? check;
945
+ if ((c.kind === "min" || c.check === "greater_than" || c.type === "min") && typeof c.value === "number")
946
+ return c.value;
947
+ if (typeof c.minimum === "number") return c.minimum;
948
+ }
949
+ return void 0;
950
+ }
951
+ function isObject(value) {
952
+ return typeof value === "object" && value !== null && !Array.isArray(value);
953
+ }
954
+ function isFileField(key, fullPath) {
955
+ return key === "file" || key.endsWith("file") || key.includes("avatar") || fullPath.includes("formdata");
956
+ }
957
+ function defaultFileValue() {
958
+ if (typeof Blob !== "undefined") {
959
+ return new Blob(["typefetch-test-file"], { type: "text/plain" });
960
+ }
961
+ return "typefetch-test-file";
962
+ }
963
+
964
+ // src/modules/tester/reporter.ts
965
+ function createMarkdownReport(report) {
966
+ const lines = [];
967
+ lines.push("# TypeFetch API Test Report");
968
+ lines.push("");
969
+ lines.push(`Generated at: ${report.generatedAt}`);
970
+ lines.push(`Mode: ${report.mode}`);
971
+ lines.push("");
972
+ lines.push("## Summary");
973
+ lines.push("");
974
+ lines.push("| Total | Passed | Failed | Skipped | Duration |");
975
+ lines.push("|---:|---:|---:|---:|---:|");
976
+ lines.push(
977
+ `| ${report.summary.total} | ${report.summary.passed} | ${report.summary.failed} | ${report.summary.skipped} | ${formatMs(report.summary.durationMs)} |`
978
+ );
979
+ lines.push("");
980
+ const failed = report.results.filter((item) => item.status === "failed");
981
+ if (failed.length) {
982
+ lines.push("## Failed Endpoints");
983
+ lines.push("");
984
+ for (const item of failed) {
985
+ lines.push(`### ${item.module}.${item.endpoint} \u2014 ${item.caseName}`);
986
+ lines.push("");
987
+ lines.push(`- Phase: ${item.phase}`);
988
+ lines.push(`- Method: ${item.method}`);
989
+ lines.push(`- Path: ${item.path}`);
990
+ lines.push(`- Duration: ${formatMs(item.durationMs)}`);
991
+ if (item.error?.status) lines.push(`- HTTP Status: ${item.error.status}`);
992
+ if (item.error?.code) lines.push(`- Code: ${item.error.code}`);
993
+ lines.push(`- Error: ${escapeMarkdown(item.error?.message ?? "Unknown error")}`);
994
+ if (item.error?.issues) {
995
+ lines.push("");
996
+ lines.push("```json");
997
+ lines.push(JSON.stringify(item.error.issues, null, 2));
998
+ lines.push("```");
999
+ }
1000
+ lines.push("");
1001
+ }
1002
+ }
1003
+ lines.push("## All Results");
1004
+ lines.push("");
1005
+ lines.push("| Status | Endpoint | Case | Phase | Method | Path | Duration |");
1006
+ lines.push("|---|---|---|---|---|---|---:|");
1007
+ for (const item of report.results) {
1008
+ lines.push(
1009
+ `| ${item.status} | ${item.module}.${item.endpoint} | ${escapeTable(item.caseName)} | ${item.phase} | ${item.method} | ${escapeTable(item.path)} | ${formatMs(item.durationMs)} |`
1010
+ );
1011
+ }
1012
+ lines.push("");
1013
+ return lines.join("\n");
1014
+ }
1015
+ function createHtmlReport(report) {
1016
+ const rows = report.results.map(
1017
+ (item) => `
1018
+ <tr class="${item.status}">
1019
+ <td>${escapeHtml(item.status)}</td>
1020
+ <td>${escapeHtml(`${item.module}.${item.endpoint}`)}</td>
1021
+ <td>${escapeHtml(item.caseName)}</td>
1022
+ <td>${escapeHtml(item.phase)}</td>
1023
+ <td>${escapeHtml(item.method)}</td>
1024
+ <td>${escapeHtml(item.path)}</td>
1025
+ <td>${formatMs(item.durationMs)}</td>
1026
+ <td>${escapeHtml(item.error?.message ?? "")}</td>
1027
+ </tr>`
1028
+ ).join("\n");
1029
+ return `<!doctype html>
1030
+ <html lang="en">
1031
+ <head>
1032
+ <meta charset="utf-8" />
1033
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1034
+ <title>TypeFetch API Test Report</title>
1035
+ <style>
1036
+ body { font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; margin: 32px; background: #0f1115; color: #f4f4f5; }
1037
+ .cards { display: flex; gap: 12px; flex-wrap: wrap; margin: 24px 0; }
1038
+ .card { background: #181b22; border: 1px solid #2a2f3a; border-radius: 14px; padding: 16px 18px; min-width: 120px; }
1039
+ .card strong { display: block; font-size: 24px; margin-top: 6px; }
1040
+ table { width: 100%; border-collapse: collapse; background: #181b22; border-radius: 14px; overflow: hidden; }
1041
+ th, td { padding: 11px 12px; border-bottom: 1px solid #2a2f3a; text-align: left; vertical-align: top; }
1042
+ th { color: #a1a1aa; font-size: 13px; }
1043
+ tr.passed td:first-child { color: #34d399; }
1044
+ tr.failed td:first-child { color: #fb7185; }
1045
+ tr.skipped td:first-child { color: #fbbf24; }
1046
+ code { background: #272b35; padding: 2px 5px; border-radius: 6px; }
1047
+ </style>
1048
+ </head>
1049
+ <body>
1050
+ <h1>TypeFetch API Test Report</h1>
1051
+ <p>Generated at: <code>${escapeHtml(report.generatedAt)}</code> \xB7 Mode: <code>${escapeHtml(report.mode)}</code></p>
1052
+ <section class="cards">
1053
+ <div class="card">Total<strong>${report.summary.total}</strong></div>
1054
+ <div class="card">Passed<strong>${report.summary.passed}</strong></div>
1055
+ <div class="card">Failed<strong>${report.summary.failed}</strong></div>
1056
+ <div class="card">Skipped<strong>${report.summary.skipped}</strong></div>
1057
+ <div class="card">Duration<strong>${formatMs(report.summary.durationMs)}</strong></div>
1058
+ </section>
1059
+ <table>
1060
+ <thead>
1061
+ <tr><th>Status</th><th>Endpoint</th><th>Case</th><th>Phase</th><th>Method</th><th>Path</th><th>Duration</th><th>Error</th></tr>
1062
+ </thead>
1063
+ <tbody>${rows}</tbody>
1064
+ </table>
1065
+ </body>
1066
+ </html>`;
1067
+ }
1068
+ function formatMs(ms) {
1069
+ return ms < 1e3 ? `${ms}ms` : `${(ms / 1e3).toFixed(2)}s`;
1070
+ }
1071
+ function escapeTable(value) {
1072
+ return value.replace(/\|/g, "\\|");
1073
+ }
1074
+ function escapeMarkdown(value) {
1075
+ return value.replace(/`/g, "\\`");
1076
+ }
1077
+ function escapeHtml(value) {
1078
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1079
+ }
1080
+
1081
+ // src/modules/tester/runner.ts
1082
+ import { z as z3 } from "zod";
1083
+ var DEFAULT_OPTIONS = {
1084
+ mode: "live",
1085
+ timeout: 1e4,
1086
+ concurrency: 1,
1087
+ stopOnFail: false,
1088
+ includeDestructive: false
1089
+ };
1090
+ function createApiTestRunner(config) {
1091
+ return new ApiTestRunner(config);
1092
+ }
1093
+ var ApiTestRunner = class {
1094
+ constructor(config) {
1095
+ __publicField(this, "config", config);
1096
+ __publicField(this, "ctx");
1097
+ __publicField(this, "options");
1098
+ this.ctx = new TypeFetchTestContext(config.context);
1099
+ this.options = {
1100
+ ...DEFAULT_OPTIONS,
1101
+ ...config.options ?? {}
1102
+ };
1103
+ }
1104
+ async run() {
1105
+ const startedAt = Date.now();
1106
+ const endpoints = this.discoverEndpoints();
1107
+ const results = [];
1108
+ for (const item of endpoints) {
1109
+ const endpointResults = await this.runEndpoint(item);
1110
+ results.push(...endpointResults);
1111
+ if (this.options.stopOnFail && endpointResults.some((result) => result.status === "failed")) {
1112
+ break;
1113
+ }
1114
+ }
1115
+ const durationMs = Date.now() - startedAt;
1116
+ return {
1117
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1118
+ mode: this.options.mode,
1119
+ summary: {
1120
+ total: results.length,
1121
+ passed: results.filter((item) => item.status === "passed").length,
1122
+ failed: results.filter((item) => item.status === "failed").length,
1123
+ skipped: results.filter((item) => item.status === "skipped").length,
1124
+ durationMs
1125
+ },
1126
+ results
1127
+ };
1128
+ }
1129
+ discoverEndpoints() {
1130
+ const endpoints = [];
1131
+ for (const moduleName of Object.keys(this.config.contracts)) {
1132
+ const module = this.config.contracts[moduleName];
1133
+ for (const endpointName of Object.keys(module)) {
1134
+ endpoints.push({
1135
+ moduleName,
1136
+ endpointName,
1137
+ endpoint: module[endpointName]
1138
+ });
1139
+ }
1140
+ }
1141
+ return endpoints;
1142
+ }
1143
+ async runEndpoint(item) {
1144
+ const { endpoint } = item;
1145
+ const testConfig = endpoint.test;
1146
+ const tags = [...testConfig?.tags ?? []];
1147
+ const destructive = Boolean(testConfig?.destructive);
1148
+ const baseMeta = {
1149
+ module: item.moduleName,
1150
+ endpoint: item.endpointName,
1151
+ method: endpoint.method,
1152
+ path: endpoint.path,
1153
+ tags,
1154
+ destructive
1155
+ };
1156
+ const skipReason = this.getEndpointSkipReason(testConfig);
1157
+ if (skipReason) {
1158
+ return [
1159
+ {
1160
+ ...baseMeta,
1161
+ caseName: "default",
1162
+ phase: this.options.mode,
1163
+ status: "skipped",
1164
+ durationMs: 0,
1165
+ skipReason
1166
+ }
1167
+ ];
1168
+ }
1169
+ try {
1170
+ await testConfig?.setup?.(this.ctx);
1171
+ } catch (error) {
1172
+ return [
1173
+ {
1174
+ ...baseMeta,
1175
+ caseName: "setup",
1176
+ phase: this.options.mode,
1177
+ status: "failed",
1178
+ durationMs: 0,
1179
+ error: normalizeError(error)
1180
+ }
1181
+ ];
1182
+ }
1183
+ const cases = this.getCases(endpoint, testConfig);
1184
+ const results = [];
1185
+ for (let index = 0; index < cases.length; index++) {
1186
+ const testCase = cases[index];
1187
+ const caseName = testCase.name ?? `case-${index + 1}`;
1188
+ if (testCase.skip) {
1189
+ results.push({
1190
+ ...baseMeta,
1191
+ caseName,
1192
+ phase: this.options.mode,
1193
+ status: "skipped",
1194
+ durationMs: 0,
1195
+ skipReason: typeof testCase.skip === "string" ? testCase.skip : "Case skipped"
1196
+ });
1197
+ continue;
1198
+ }
1199
+ const phases = this.getPhases(endpoint);
1200
+ for (const phase of phases) {
1201
+ const result = await this.runCasePhase(item, testCase, caseName, phase);
1202
+ results.push(result);
1203
+ if (this.options.stopOnFail && result.status === "failed") break;
1204
+ }
1205
+ }
1206
+ try {
1207
+ await testConfig?.teardown?.(this.ctx);
1208
+ } catch (error) {
1209
+ results.push({
1210
+ ...baseMeta,
1211
+ caseName: "teardown",
1212
+ phase: this.options.mode,
1213
+ status: "failed",
1214
+ durationMs: 0,
1215
+ error: normalizeError(error)
1216
+ });
1217
+ }
1218
+ return results;
1219
+ }
1220
+ getEndpointSkipReason(testConfig) {
1221
+ if (testConfig?.enabled === false) return "Endpoint tests disabled";
1222
+ if (testConfig?.destructive && !this.options.includeDestructive) return "Destructive endpoint skipped";
1223
+ const tags = testConfig?.tags ?? [];
1224
+ if (this.options.includeTags?.length && !tags.some((tag) => this.options.includeTags.includes(tag))) {
1225
+ return "Endpoint does not match includeTags";
1226
+ }
1227
+ if (this.options.excludeTags?.length && tags.some((tag) => this.options.excludeTags.includes(tag))) {
1228
+ return "Endpoint matches excludeTags";
1229
+ }
1230
+ return void 0;
1231
+ }
1232
+ getCases(endpoint, testConfig) {
1233
+ if (testConfig?.cases?.length) return testConfig.cases;
1234
+ if (testConfig?.input) return [{ name: "default", input: testConfig.input }];
1235
+ return [
1236
+ {
1237
+ name: "auto-generated",
1238
+ input: generateInput(endpoint.request, this.options.autoInput)
1239
+ }
1240
+ ];
1241
+ }
1242
+ getPhases(endpoint) {
1243
+ switch (this.options.mode) {
1244
+ case "schema":
1245
+ return ["schema"];
1246
+ case "mock":
1247
+ return ["mock"];
1248
+ case "full":
1249
+ return endpoint.mockData ? ["schema", "mock", "live"] : ["schema", "live"];
1250
+ case "live":
1251
+ default:
1252
+ return ["live"];
1253
+ }
1254
+ }
1255
+ async runCasePhase(item, testCase, caseName, phase) {
1256
+ const { endpoint, moduleName, endpointName } = item;
1257
+ const startedAt = Date.now();
1258
+ let input;
1259
+ const meta = {
1260
+ module: moduleName,
1261
+ endpoint: endpointName,
1262
+ caseName,
1263
+ phase,
1264
+ method: endpoint.method,
1265
+ path: endpoint.path,
1266
+ tags: endpoint.test?.tags ?? [],
1267
+ destructive: Boolean(endpoint.test?.destructive)
1268
+ };
1269
+ try {
1270
+ input = await resolveInput(endpoint, testCase, this.ctx, this.options.autoInput);
1271
+ const parsedInput = endpoint.request.parse(input);
1272
+ if (phase === "schema") {
1273
+ return {
1274
+ ...meta,
1275
+ status: "passed",
1276
+ durationMs: Date.now() - startedAt,
1277
+ input: parsedInput
1278
+ };
1279
+ }
1280
+ if (phase === "mock") {
1281
+ if (!endpoint.mockData) {
1282
+ return {
1283
+ ...meta,
1284
+ status: "skipped",
1285
+ durationMs: Date.now() - startedAt,
1286
+ input: parsedInput,
1287
+ skipReason: "No mockData configured for endpoint"
1288
+ };
1289
+ }
1290
+ const mockResponse = typeof endpoint.mockData === "function" ? endpoint.mockData() : endpoint.mockData;
1291
+ const parsedResponse = endpoint.response.parse(mockResponse);
1292
+ await testCase.expect?.({ input: parsedInput, response: parsedResponse, ctx: this.ctx });
1293
+ return {
1294
+ ...meta,
1295
+ status: "passed",
1296
+ durationMs: Date.now() - startedAt,
1297
+ input: parsedInput,
1298
+ response: parsedResponse
1299
+ };
1300
+ }
1301
+ const response = await this.callClient(moduleName, endpointName, parsedInput, testCase);
1302
+ await testCase.expect?.({ input: parsedInput, response, ctx: this.ctx });
1303
+ return {
1304
+ ...meta,
1305
+ status: "passed",
1306
+ durationMs: Date.now() - startedAt,
1307
+ input: parsedInput,
1308
+ response
1309
+ };
1310
+ } catch (error) {
1311
+ const normalized = normalizeError(error);
1312
+ const expectedStatuses = toStatusList(testCase.expectStatus);
1313
+ const expectedErrorStatus = normalized.status && expectedStatuses.includes(normalized.status);
1314
+ if (expectedErrorStatus) {
1315
+ return {
1316
+ ...meta,
1317
+ status: "passed",
1318
+ durationMs: Date.now() - startedAt,
1319
+ input,
1320
+ error: normalized
1321
+ };
1322
+ }
1323
+ return {
1324
+ ...meta,
1325
+ status: "failed",
1326
+ durationMs: Date.now() - startedAt,
1327
+ input,
1328
+ error: normalized
1329
+ };
1330
+ }
1331
+ }
1332
+ async callClient(moduleName, endpointName, input, testCase) {
1333
+ const fn = this.config.client.modules[moduleName]?.[endpointName];
1334
+ if (!fn) throw new Error(`Client method not found: ${moduleName}.${endpointName}`);
1335
+ const requestOptions = {
1336
+ ...this.options.requestOptions ?? {},
1337
+ timeout: testCase.timeout ?? this.options.timeout
1338
+ };
1339
+ return fn(input, requestOptions);
1340
+ }
1341
+ };
1342
+ async function resolveInput(endpoint, testCase, ctx, autoInputOptions) {
1343
+ if (typeof testCase.input === "function") return testCase.input(ctx);
1344
+ if (testCase.input !== void 0) return testCase.input;
1345
+ return generateInput(endpoint.request, autoInputOptions);
1346
+ }
1347
+ function normalizeError(error) {
1348
+ if (error instanceof z3.ZodError) {
1349
+ const zodError = error;
1350
+ return {
1351
+ name: zodError.name,
1352
+ message: `Validation error: ${zodError.issues.map((issue) => issue.message).join(", ")}`,
1353
+ code: "VALIDATION_ERROR",
1354
+ issues: zodError.issues,
1355
+ stack: zodError.stack
1356
+ };
1357
+ }
1358
+ if (error instanceof Error) {
1359
+ const anyError = error;
1360
+ return {
1361
+ name: error.name,
1362
+ message: error.message,
1363
+ status: anyError.status,
1364
+ code: anyError.code,
1365
+ issues: anyError.issues ?? anyError.errors,
1366
+ stack: error.stack
1367
+ };
1368
+ }
1369
+ return { message: String(error) };
1370
+ }
1371
+ function toStatusList(status) {
1372
+ if (status === void 0) return [];
1373
+ return Array.isArray(status) ? status : [status];
1374
+ }
1375
+
1376
+ // src/cli/config.ts
1377
+ function defineTypeFetchTestConfig(config) {
1378
+ return config;
1379
+ }
694
1380
  export {
695
1381
  ApiClient,
1382
+ ApiTestRunner,
696
1383
  RichError,
1384
+ TypeFetchTestContext,
697
1385
  authMiddleware,
698
1386
  cacheMiddleware,
1387
+ createApiTestRunner,
1388
+ createHtmlReport,
1389
+ createMarkdownReport,
1390
+ defineTypeFetchTestConfig,
699
1391
  encryptionMiddleware,
1392
+ generateInput,
700
1393
  loggingMiddleware,
701
1394
  makeRequestSchema,
702
1395
  processDeep,