@apifn/core 0.1.0 → 0.2.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.cjs CHANGED
@@ -52,6 +52,7 @@ __export(src_exports, {
52
52
  mintTestToken: () => mintTestToken,
53
53
  parseOpenAPI: () => parseOpenAPI,
54
54
  upconvertFrom3_0: () => upconvertFrom3_0,
55
+ validateAndDereferenceOpenAPI: () => validateAndDereferenceOpenAPI,
55
56
  validateOpenAPI: () => validateOpenAPI
56
57
  });
57
58
  module.exports = __toCommonJS(src_exports);
@@ -730,6 +731,420 @@ function parseOpenAPI(input) {
730
731
 
731
732
  // src/openapi/validate.ts
732
733
  var import_swagger_parser = __toESM(require("@apidevtools/swagger-parser"), 1);
734
+ var import_yaml2 = require("yaml");
735
+
736
+ // src/openapi/reference-context.ts
737
+ var REFERENCE_MODES = /* @__PURE__ */ new Set(["object", "example", "link"]);
738
+ var OBJECT_MAPS = /* @__PURE__ */ new Set(["parameters", "requestBodies", "headers", "securitySchemes", "callbacks", "responses"]);
739
+ var NAME_MAPS = /* @__PURE__ */ new Set([
740
+ "properties",
741
+ "patternProperties",
742
+ "$defs",
743
+ "definitions",
744
+ "dependentSchemas",
745
+ "schemas",
746
+ "links",
747
+ "pathItems",
748
+ "paths",
749
+ "webhooks",
750
+ "content",
751
+ "encoding",
752
+ "variables"
753
+ ]);
754
+ var LITERALS = /* @__PURE__ */ new Set(["example", "default", "const", "enum"]);
755
+ function childMode(key, value) {
756
+ if (LITERALS.has(key) || key.startsWith("x-")) return "literal";
757
+ if (key === "examples") return Array.isArray(value) ? "literal" : "examples";
758
+ if (key === "components") return "components";
759
+ if (key === "links") return "links";
760
+ if (key === "paths") return "extNames";
761
+ if (key === "responses") return "extObjects";
762
+ if (key === "requestBody") return "object";
763
+ if (OBJECT_MAPS.has(key)) return "objects";
764
+ return NAME_MAPS.has(key) ? "names" : "node";
765
+ }
766
+ function entryMode(mode, key, value) {
767
+ switch (mode) {
768
+ case "names":
769
+ return "node";
770
+ case "extNames":
771
+ return key.startsWith("x-") ? "literal" : "node";
772
+ case "objects":
773
+ return "object";
774
+ case "extObjects":
775
+ return key.startsWith("x-") ? "literal" : "object";
776
+ case "components":
777
+ if (key.startsWith("x-")) return "literal";
778
+ if (key === "examples" || key === "links") return key;
779
+ return OBJECT_MAPS.has(key) ? "objects" : "names";
780
+ case "examples":
781
+ return "example";
782
+ case "links":
783
+ return "link";
784
+ case "link":
785
+ return key === "parameters" || key === "requestBody" ? "literal" : childMode(key, value);
786
+ default:
787
+ return null;
788
+ }
789
+ }
790
+ var MAP_MODES = /* @__PURE__ */ new Set(["names", "extNames", "objects", "extObjects", "components", "examples", "links"]);
791
+ var MAP_ITEMS = { names: "node", extNames: "node", objects: "object", extObjects: "object" };
792
+ var openAPIReferenceContext = Object.freeze({
793
+ childMode,
794
+ entryMode,
795
+ isReferenceObject: (mode) => REFERENCE_MODES.has(mode),
796
+ isMap: (mode) => MAP_MODES.has(mode),
797
+ arrayItemMode: (mode) => MAP_ITEMS[mode] ?? mode
798
+ });
799
+
800
+ // src/openapi/validate.ts
801
+ var EXTERNAL_REF_ERROR = "External OpenAPI $ref requires an explicit allowlist entry";
802
+ function referenceChildMode(parent, mode, key, child) {
803
+ const { childMode: childMode2, entryMode: entryMode2, arrayItemMode } = openAPIReferenceContext;
804
+ if (Array.isArray(parent)) return arrayItemMode(mode);
805
+ if (mode === "literal" || mode === "example") return "literal";
806
+ return entryMode2(mode, key, child) ?? childMode2(key, child);
807
+ }
808
+ var ReferencePreparationError = class extends Error {
809
+ path;
810
+ constructor(site, cause) {
811
+ super(cause instanceof Error ? cause.message : "OpenAPI ref could not be prepared", { cause });
812
+ this.path = [...pathKeys(site), "$ref"].join(".");
813
+ }
814
+ };
815
+ function pathKeys(path) {
816
+ const segments = [];
817
+ for (let cursor = path; cursor; cursor = cursor.parent) segments.push(cursor.key);
818
+ return segments.reverse();
819
+ }
820
+ function parsePreloadedDocument(contents) {
821
+ const parsed = (0, import_yaml2.parseDocument)(contents);
822
+ if (parsed.errors.length) throw new Error(parsed.errors[0].message);
823
+ const mergeTag = "tag:yaml.org,2002:merge";
824
+ const implicitMerge = parsed.schema.tags.some((tag) => tag.tag === mergeTag && tag.default);
825
+ let hasAliases = false;
826
+ let sourceNodes = 0;
827
+ (0, import_yaml2.visit)(parsed, (_key, node) => {
828
+ sourceNodes += 1;
829
+ hasAliases ||= (0, import_yaml2.isAlias)(node);
830
+ if ((0, import_yaml2.isPair)(node) && (0, import_yaml2.isScalar)(node.key)) {
831
+ const { tag, type, value: value2 } = node.key;
832
+ const mergeKey = value2 === "<<" || typeof value2 === "symbol" && value2.description === "<<";
833
+ if (tag === mergeTag || implicitMerge && (!type || type === "PLAIN") && mergeKey) {
834
+ throw new Error("YAML merge keys are unsupported in preloaded OpenAPI documents");
835
+ }
836
+ }
837
+ });
838
+ const value = parsed.toJS({ maxAliasCount: -1 });
839
+ if (!hasAliases) return value;
840
+ const limit = sourceNodes * 100;
841
+ const weights = /* @__PURE__ */ new WeakMap();
842
+ function count(node) {
843
+ if (typeof node !== "object" || node === null) return 1;
844
+ const cached = weights.get(node);
845
+ if (cached !== void 0) return cached;
846
+ weights.set(node, limit + 1);
847
+ let size = 1;
848
+ for (const child of Object.values(node)) {
849
+ size += count(child);
850
+ if (size > limit) throw new Error("Excessive YAML alias expansion in preloaded OpenAPI document");
851
+ }
852
+ weights.set(node, size);
853
+ return size;
854
+ }
855
+ count(value);
856
+ return value;
857
+ }
858
+ function decodeFragment(fragment) {
859
+ try {
860
+ return decodeURIComponent(fragment);
861
+ } catch {
862
+ return fragment;
863
+ }
864
+ }
865
+ function unescapePointerToken(token) {
866
+ return token.replaceAll("~1", "/").replaceAll("~0", "~");
867
+ }
868
+ function encodePointer(tokens) {
869
+ return "#" + tokens.map(
870
+ (token) => "/" + encodeURIComponent(token.replaceAll("~", "~0").replaceAll("/", "~1"))
871
+ ).join("");
872
+ }
873
+ function pointerMember(parent, tokens, index) {
874
+ const key = tokens[index];
875
+ if (!Object.hasOwn(parent, key) || Reflect.get(parent, key) === void 0 || index === tokens.length - 1 && Reflect.get(parent, key) === null) {
876
+ for (let end = tokens.length; end > index + 1; end -= 1) {
877
+ const joined = tokens.slice(index, end).join("/");
878
+ if (Object.hasOwn(parent, joined) && Reflect.get(parent, joined) !== void 0) {
879
+ return { key: joined, index: end - 1 };
880
+ }
881
+ }
882
+ }
883
+ return Object.hasOwn(parent, key) ? { key, index } : void 0;
884
+ }
885
+ var LOCAL_PATH_ORIGIN = "https://apifn-local-path.invalid";
886
+ var WINDOWS_DRIVE_PATH = /^[a-z]:[\\/]/i;
887
+ var WINDOWS_SHARE_PATH = /^\\\\([^\\/]+)[\\/]([^\\/]+)(?:[\\/]|$)/;
888
+ function workingDirectoryLocation() {
889
+ const cwd = typeof process !== "undefined" && process.cwd ? process.cwd() : "/";
890
+ const share = WINDOWS_SHARE_PATH.exec(cwd);
891
+ const windowsPath = share ? "C:\\" + cwd.slice(share[0].length) : cwd;
892
+ const isWindowsPath = WINDOWS_DRIVE_PATH.test(windowsPath);
893
+ if (isWindowsPath) {
894
+ const [drive, ...segments] = windowsPath.replaceAll("\\", "/").split("/");
895
+ const directory = segments.map(encodeURIComponent).join("/").replace(/\/$/, "");
896
+ const url2 = new URL("file:///" + drive + "/" + (directory ? directory + "/" : ""));
897
+ const shareRoot = share ? absolutePathKey("//" + [share[1], share[2]].map(encodeURIComponent).join("/")) : void 0;
898
+ return { url: url2, isPath: true, isWindowsPath, shareRoot };
899
+ }
900
+ const path = (cwd.startsWith("/") ? cwd : "/" + cwd).replace(/\/$/, "") + "/";
901
+ const url = new URL(LOCAL_PATH_ORIGIN);
902
+ url.pathname = path.split("/").map(encodeURIComponent).join("/");
903
+ return { url, isPath: true, isWindowsPath };
904
+ }
905
+ function absolutePathKey(pathname) {
906
+ return pathname.split("/").map(
907
+ (segment) => decodeURIComponent(segment).replaceAll("%", "%25").replaceAll("?", "%3F").replaceAll("/", "%2F").replaceAll("\\", "%5C")
908
+ ).join("/");
909
+ }
910
+ function resolveDocumentURI(base, ref) {
911
+ const pathEnd = ref.search(/[?#]/);
912
+ const refPath = pathEnd < 0 ? ref : ref.slice(0, pathEnd);
913
+ const normalized = refPath.replaceAll("\\", "/") + ref.slice(refPath.length);
914
+ const windowsDrive = WINDOWS_DRIVE_PATH.test(normalized);
915
+ const share = WINDOWS_SHARE_PATH.exec(refPath);
916
+ const windowsPath = share ? "C:/" + normalized.slice(share[0].length) : normalized;
917
+ const isAbsoluteWindowsPath = windowsDrive || share !== null;
918
+ const url = isAbsoluteWindowsPath ? new URL("file:///" + windowsPath) : new URL(normalized, base.url);
919
+ const absolute = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(normalized.trimStart());
920
+ const fragment = url.hash.slice(1);
921
+ url.hash = "";
922
+ const isPath = isAbsoluteWindowsPath || base.isPath && !absolute && url.origin === base.url.origin;
923
+ const queryStart = url.href.indexOf("?");
924
+ const query = queryStart < 0 ? "" : url.href.slice(queryStart);
925
+ const pathname = isPath ? absolutePathKey(url.pathname) : void 0;
926
+ const uri = pathname === void 0 ? url.href : pathname + query;
927
+ const pathWithoutLeadingSlash = pathname?.slice(1);
928
+ const drivePath = pathWithoutLeadingSlash !== void 0 && (isAbsoluteWindowsPath || base.isWindowsPath) && WINDOWS_DRIVE_PATH.test(pathWithoutLeadingSlash) ? pathWithoutLeadingSlash : void 0;
929
+ const shareRoot = share ? absolutePathKey("//" + share[1] + "/" + share[2]) : drivePath !== void 0 && !windowsDrive ? base.shareRoot : void 0;
930
+ const resolvedPath = shareRoot && drivePath ? shareRoot + drivePath.slice(2) : drivePath;
931
+ const keys = resolvedPath === void 0 ? [uri] : [resolvedPath + query, resolvedPath.replaceAll("/", "\\") + query];
932
+ return { uri: keys[0], fragment, keys, location: { url, isPath, isWindowsPath: drivePath !== void 0, shareRoot } };
933
+ }
934
+ var EXAMPLE_FIELDS = /* @__PURE__ */ new Set(["value", "externalValue", "summary", "description"]);
935
+ function isStandaloneExample(value) {
936
+ return typeof value === "object" && value !== null && !Array.isArray(value) && (Object.hasOwn(value, "value") || Object.hasOwn(value, "externalValue")) && Object.keys(value).every((key) => EXAMPLE_FIELDS.has(key) || key.startsWith("x-"));
937
+ }
938
+ function restoreReferenceCopies(document, { field, targets, originals }) {
939
+ if (!originals.size) return;
940
+ const seen = /* @__PURE__ */ new WeakSet();
941
+ const pending = [document];
942
+ while (pending.length) {
943
+ const value = pending.pop();
944
+ if (typeof value !== "object" || value === null || seen.has(value)) continue;
945
+ seen.add(value);
946
+ if (Reflect.get(value, field) === targets) Reflect.deleteProperty(value, field);
947
+ if ("$ref" in value && typeof value.$ref === "string") {
948
+ const original = originals.get(value.$ref);
949
+ if (original !== void 0) value.$ref = original;
950
+ }
951
+ for (const child of Object.values(value)) pending.push(child);
952
+ }
953
+ }
954
+ function prepareReferences(document, externalReferences) {
955
+ const root = { value: document, location: workingDirectoryLocation() };
956
+ const supplied = /* @__PURE__ */ new Map();
957
+ const literalReferences = /* @__PURE__ */ new Map();
958
+ const seen = /* @__PURE__ */ new WeakMap();
959
+ const pending = [];
960
+ let field = "x-apifn-reference-copies";
961
+ while (Object.hasOwn(document, field)) field += "-";
962
+ const referenceCopies = { field, targets: [], originals: /* @__PURE__ */ new Map() };
963
+ const copiedPointers = /* @__PURE__ */ new Map();
964
+ const aliasTargets = /* @__PURE__ */ new WeakMap();
965
+ function errorAtReference(site, error) {
966
+ if (error instanceof ReferencePreparationError) return error;
967
+ return new ReferencePreparationError(site, error);
968
+ }
969
+ function enqueue(target) {
970
+ const { value, mode } = target;
971
+ if (typeof value !== "object" || value === null) return value;
972
+ const contexts = seen.get(value) ?? /* @__PURE__ */ new Map();
973
+ const existing = contexts.get(mode);
974
+ if (existing) return existing;
975
+ const prototype = Object.getPrototypeOf(value);
976
+ const copy2 = Array.isArray(value) ? [...value] : prototype === Object.prototype || prototype === null ? { ...value } : value;
977
+ contexts.set(mode, copy2);
978
+ seen.set(value, contexts);
979
+ pending.push({ ...target, value, copy: copy2 });
980
+ return copy2;
981
+ }
982
+ function location(source, ref) {
983
+ if (ref.startsWith("#") || source !== root && ref === "") return { source, fragment: ref.slice(1) };
984
+ if (!externalReferences?.size) throw new Error(EXTERNAL_REF_ERROR);
985
+ const { uri: key, fragment, keys, location: targetLocation } = resolveDocumentURI(source.location, ref);
986
+ let external = supplied.get(key);
987
+ if (!external) {
988
+ const contents = keys.map((candidate) => externalReferences.get(candidate)).find((value) => value !== void 0);
989
+ if (contents === void 0) throw new Error(EXTERNAL_REF_ERROR);
990
+ external = { value: parsePreloadedDocument(contents), location: targetLocation };
991
+ supplied.set(key, external);
992
+ }
993
+ return { source: external, fragment };
994
+ }
995
+ function pointerTarget(source, tokens, { aliases = /* @__PURE__ */ new Set(), directAlias, importSite: outerSite }) {
996
+ let value = source.value;
997
+ let mode = "node";
998
+ let path;
999
+ let importSite;
1000
+ let throughLiteralAlias = false;
1001
+ const matched = [];
1002
+ const unresolved = (index, target) => ({ tokens: [...matched, ...tokens.slice(index)], target });
1003
+ for (let index = 0; index < tokens.length; index += 1) {
1004
+ const chain = new Set(aliases);
1005
+ const overrides = /* @__PURE__ */ new Map();
1006
+ while (typeof value === "object" && value !== null && "$ref" in value && typeof value.$ref === "string" && (value.$ref || source !== root)) {
1007
+ if (mode === "literal") {
1008
+ if (source !== root || !value.$ref.startsWith("#") || pointerMember(value, tokens, index)) break;
1009
+ throughLiteralAlias = true;
1010
+ }
1011
+ if (chain.has(value)) {
1012
+ if (value === directAlias || Object.hasOwn(value, tokens[index])) break;
1013
+ throw new Error("Circular OpenAPI $ref aliases cannot be traversed");
1014
+ }
1015
+ chain.add(value);
1016
+ let target = aliasTargets.get(value);
1017
+ if (!target) {
1018
+ const site = source === root ? { path } : importSite ?? outerSite;
1019
+ let lookup;
1020
+ try {
1021
+ const alias = location(source, value.$ref);
1022
+ lookup = lookupPointer(alias.source, alias.fragment, { aliases: chain, directAlias: value, importSite: site });
1023
+ } catch (error) {
1024
+ throw errorAtReference(site?.path, error);
1025
+ }
1026
+ if (!lookup.target || lookup.target === "reference") return unresolved(index, "reference");
1027
+ target = lookup.target;
1028
+ aliasTargets.set(value, target);
1029
+ }
1030
+ if (target.value === value) break;
1031
+ for (const [key2, sibling2] of Object.entries(value)) {
1032
+ if (key2 !== "$ref" && !overrides.has(key2)) {
1033
+ overrides.set(key2, { value: sibling2, mode: referenceChildMode(value, mode, key2, sibling2), source, path, importSite });
1034
+ }
1035
+ }
1036
+ if ((mode === "node" || mode === "literal") && target.mode !== "literal") mode = target.mode;
1037
+ const aliasSite = source === root ? { path } : importSite;
1038
+ source = target.source;
1039
+ importSite = source === root ? void 0 : target.importSite ?? aliasSite;
1040
+ path = target.path;
1041
+ value = target.value;
1042
+ }
1043
+ if (typeof value !== "object" || value === null) return unresolved(index);
1044
+ const parent = overrides.size ? { ...value, ...Object.fromEntries([...overrides].map(([key2, entry]) => [key2, entry.value])) } : value;
1045
+ if (source !== root && mode === "node" && isStandaloneExample(parent)) mode = "example";
1046
+ const member = pointerMember(parent, tokens, index);
1047
+ if (!member) {
1048
+ if (value === root.value && tokens[index] === field) throw new Error("OpenAPI $ref target does not exist");
1049
+ return unresolved(index);
1050
+ }
1051
+ const { key } = member;
1052
+ index = member.index;
1053
+ matched.push(key);
1054
+ const child = Reflect.get(parent, key);
1055
+ const sibling = overrides.get(key);
1056
+ if (sibling) {
1057
+ source = sibling.source;
1058
+ importSite = sibling.importSite;
1059
+ }
1060
+ path = { key, parent: sibling ? sibling.path : path };
1061
+ mode = sibling?.mode ?? referenceChildMode(parent, mode, key, child);
1062
+ value = child;
1063
+ }
1064
+ return { tokens: matched, target: { value, mode, source, path, importSite }, throughLiteralAlias };
1065
+ }
1066
+ function lookupPointer(source, fragment, options = {}) {
1067
+ if (fragment === "") return { tokens: [], target: { value: source.value, mode: "node", source } };
1068
+ if (fragment.startsWith("/")) {
1069
+ const legacy = fragment.split("/").slice(1).map((token) => source === root ? decodeFragment(unescapePointerToken(token)) : unescapePointerToken(decodeFragment(token)));
1070
+ const legacyLookup = pointerTarget(source, legacy, options);
1071
+ if (legacyLookup.target || !/%2f/i.test(fragment)) return legacyLookup;
1072
+ const decoded2 = decodeFragment(fragment).split("/").slice(1).map(unescapePointerToken);
1073
+ const decodedLookup = pointerTarget(source, decoded2, options);
1074
+ return decodedLookup.target ? decodedLookup : legacyLookup;
1075
+ }
1076
+ const decoded = decodeFragment(fragment);
1077
+ if (!decoded.startsWith("/") || source !== root && !fragment.startsWith("/")) {
1078
+ throw new Error("OpenAPI $ref fragments must be slash-delimited JSON pointers");
1079
+ }
1080
+ const tokens = decoded.split("/").slice(1).map(unescapePointerToken);
1081
+ return pointerTarget(source, tokens, options);
1082
+ }
1083
+ function rewriteReference(ref, { source, mode, value }, site) {
1084
+ const destination = location(source, ref);
1085
+ const { tokens, target, throughLiteralAlias } = lookupPointer(destination.source, destination.fragment, { importSite: site });
1086
+ const canonical = encodePointer(tokens);
1087
+ const isLocal = destination.source === root;
1088
+ if (!target || target === "reference") {
1089
+ if (isLocal) return canonical;
1090
+ throw new Error("OpenAPI $ref target does not exist");
1091
+ }
1092
+ if (source !== root && target.source === source && target.value === value) {
1093
+ throw new Error("Preloaded OpenAPI $ref must point to a different location");
1094
+ }
1095
+ if (isLocal && target.source === root && (target.mode !== "literal" || typeof target.value !== "object" || target.value === null)) {
1096
+ return throughLiteralAlias ? encodePointer(pathKeys(target.path)) : canonical;
1097
+ }
1098
+ const pointers = copiedPointers.get(destination.source) ?? /* @__PURE__ */ new Map();
1099
+ const key = mode + canonical;
1100
+ let preparedRef = pointers.get(key);
1101
+ if (!preparedRef) {
1102
+ const targetIndex = String(referenceCopies.targets.length);
1103
+ preparedRef = "#/" + field + "/" + targetIndex;
1104
+ pointers.set(key, preparedRef);
1105
+ copiedPointers.set(destination.source, pointers);
1106
+ referenceCopies.originals.set(preparedRef, isLocal ? canonical : ref);
1107
+ referenceCopies.targets.push(enqueue({ ...target, mode, importSite: target.importSite ?? site }));
1108
+ }
1109
+ if (target.source !== root && Object.keys(value).length > 1) {
1110
+ const alias = "#/" + field + "/" + referenceCopies.targets.length;
1111
+ referenceCopies.targets.push({ $ref: preparedRef });
1112
+ referenceCopies.originals.set(alias, isLocal ? canonical : ref);
1113
+ return alias;
1114
+ }
1115
+ return preparedRef;
1116
+ }
1117
+ const copy = enqueue({ value: root.value, mode: "node", source: root });
1118
+ while (pending.length) {
1119
+ const current = pending.pop();
1120
+ const { value, copy: copy2, mode, source, path, importSite } = current;
1121
+ if ("$ref" in value && typeof value.$ref === "string") {
1122
+ if (mode === "literal") {
1123
+ literalReferences.set(copy2, value.$ref);
1124
+ Reflect.deleteProperty(copy2, "$ref");
1125
+ } else if (value.$ref || source !== root) {
1126
+ const site = source === root ? { path } : importSite;
1127
+ try {
1128
+ Reflect.set(copy2, "$ref", rewriteReference(value.$ref, current, site));
1129
+ } catch (error) {
1130
+ throw errorAtReference(site?.path, error);
1131
+ }
1132
+ }
1133
+ }
1134
+ for (const [key, child] of Object.entries(value)) {
1135
+ if (key === "$ref" && typeof child === "string") continue;
1136
+ Reflect.set(copy2, key, enqueue({
1137
+ value: child,
1138
+ mode: referenceChildMode(value, mode, key, child),
1139
+ source,
1140
+ path: { key, parent: path },
1141
+ importSite
1142
+ }));
1143
+ }
1144
+ }
1145
+ if (referenceCopies.targets.length) Reflect.set(copy, field, referenceCopies.targets);
1146
+ return { copy, referenceCopies, literalReferences };
1147
+ }
733
1148
  function toValidationErrors(error) {
734
1149
  const details = error?.details;
735
1150
  if (Array.isArray(details) && details.length > 0) {
@@ -742,18 +1157,29 @@ function toValidationErrors(error) {
742
1157
  const message = error instanceof Error ? error.message : "Validation error";
743
1158
  return [
744
1159
  {
745
- path: "openapi",
1160
+ path: error instanceof ReferencePreparationError ? error.path : "openapi",
746
1161
  message,
747
1162
  severity: "error"
748
1163
  }
749
1164
  ];
750
1165
  }
751
- async function validateOpenAPI(document) {
1166
+ async function validateOpenAPI(document, options) {
1167
+ return (await validateAndDereferenceOpenAPI(document, options)).errors;
1168
+ }
1169
+ async function validateAndDereferenceOpenAPI(document, options) {
752
1170
  try {
753
- await import_swagger_parser.default.validate(document);
754
- return [];
1171
+ const { copy, referenceCopies, literalReferences } = prepareReferences(
1172
+ structuredClone(document),
1173
+ options?.externalReferences
1174
+ );
1175
+ const validated = await import_swagger_parser.default.validate("/apifn-validation/openapi.json", copy, {
1176
+ resolve: { external: false, file: false, http: false }
1177
+ });
1178
+ restoreReferenceCopies(validated, referenceCopies);
1179
+ for (const [literal, ref] of literalReferences) Reflect.set(literal, "$ref", ref);
1180
+ return { document: validated, errors: [] };
755
1181
  } catch (error) {
756
- return toValidationErrors(error);
1182
+ return { document: null, errors: toValidationErrors(error) };
757
1183
  }
758
1184
  }
759
1185
 
@@ -1289,6 +1715,14 @@ function createWatchFnClient(options) {
1289
1715
  })
1290
1716
  };
1291
1717
  }
1718
+ function describeError(err) {
1719
+ try {
1720
+ return err instanceof Error ? String(err.message) : String(err);
1721
+ } catch {
1722
+ return "unknown error";
1723
+ }
1724
+ }
1725
+ var UNHANDLED_ERROR_STATUS = 500;
1292
1726
  function apifnWatchMiddleware(options) {
1293
1727
  const {
1294
1728
  baseUrl,
@@ -1303,6 +1737,14 @@ function apifnWatchMiddleware(options) {
1303
1737
  Accept: "application/json"
1304
1738
  };
1305
1739
  if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
1740
+ function warn(message, err) {
1741
+ if (silent) return;
1742
+ try {
1743
+ const detail = err === void 0 ? "" : `: ${describeError(err)}`;
1744
+ console.warn(`[apifn/watchfn] ${message}${detail}`);
1745
+ } catch {
1746
+ }
1747
+ }
1306
1748
  async function sendEvent(event) {
1307
1749
  try {
1308
1750
  const controller = new AbortController();
@@ -1318,38 +1760,43 @@ function apifnWatchMiddleware(options) {
1318
1760
  } finally {
1319
1761
  clearTimeout(timer);
1320
1762
  }
1321
- if (!res.ok && !silent) {
1322
- console.warn(`[apifn/watchfn] Event POST returned HTTP ${res.status}`);
1763
+ if (!res.ok) {
1764
+ warn(`Event POST returned HTTP ${res.status}`);
1323
1765
  }
1324
1766
  } catch (err) {
1325
- if (!silent) {
1326
- const msg = err instanceof Error ? err.message : String(err);
1327
- console.warn(`[apifn/watchfn] Failed to send event to watchfn: ${msg}`);
1767
+ warn("Failed to send event to watchfn", err);
1768
+ }
1769
+ }
1770
+ async function observe(request, statusCode, start) {
1771
+ try {
1772
+ const event = {
1773
+ method: request.method,
1774
+ path: new URL(request.url).pathname,
1775
+ status_code: statusCode,
1776
+ duration_ms: Date.now() - start,
1777
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1778
+ };
1779
+ if (fireAndForget) {
1780
+ sendEvent(event).catch(() => {
1781
+ });
1782
+ } else {
1783
+ await sendEvent(event);
1328
1784
  }
1785
+ } catch (err) {
1786
+ warn("Failed to record request telemetry", err);
1329
1787
  }
1330
1788
  }
1331
- return async function watchMiddleware(req, res, next) {
1789
+ return async function watchMiddleware(request, _context, next) {
1332
1790
  const start = Date.now();
1333
- await next();
1334
- const durationMs = Date.now() - start;
1335
- const r = req;
1336
- const s = res;
1337
- const method = r.method ?? "UNKNOWN";
1338
- const path = r.path ?? (r.url ? new URL(r.url, "http://localhost").pathname : "/unknown");
1339
- const statusCode = s.statusCode ?? 200;
1340
- const event = {
1341
- method,
1342
- path,
1343
- status_code: statusCode,
1344
- duration_ms: durationMs,
1345
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1346
- };
1347
- if (fireAndForget) {
1348
- sendEvent(event).catch(() => {
1349
- });
1350
- } else {
1351
- await sendEvent(event);
1791
+ let response;
1792
+ try {
1793
+ response = await next();
1794
+ } catch (err) {
1795
+ await observe(request, UNHANDLED_ERROR_STATUS, start);
1796
+ throw err;
1352
1797
  }
1798
+ await observe(request, response.status, start);
1799
+ return response;
1353
1800
  };
1354
1801
  }
1355
1802
 
@@ -1516,6 +1963,7 @@ function createCliLogger(options = {}) {
1516
1963
  mintTestToken,
1517
1964
  parseOpenAPI,
1518
1965
  upconvertFrom3_0,
1966
+ validateAndDereferenceOpenAPI,
1519
1967
  validateOpenAPI
1520
1968
  });
1521
1969
  //# sourceMappingURL=index.cjs.map