// Sans-IO external `$ref` bundler (plan 7.6).
// Resolves relative file/URI references (e.g. `./common.yaml#/components/schemas/Error`
// or `schemas/pet.json`) via a caller-supplied loader callback and internalizes
// referenced definitions into `#/components/
/` (or inline), // keeping `spec` cross-target across native, js, wasm, and wasm-gc. ///| /// Split a `$ref` string into `(doc_uri, fragment_ref)` where `fragment_ref` /// starts with `#` (defaulting to `"#"` when no fragment is present). fn split_external_ref(ref_ : String) -> (String, String) { match ref_.find("#") { Some(idx) => { let doc_part = ref_[:idx].to_owned() let frag = ref_[idx:].to_owned() (doc_part, if frag == "" { "#" } else { frag }) } None => (ref_, "#") } } ///| /// Return true when `uri` starts with an RFC 3986 scheme (`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":"`). fn has_uri_scheme(uri : String) -> Bool { if uri.is_empty() { return false } let c0 = uri[0] if !((c0 >= 'a' && c0 <= 'z') || (c0 >= 'A' && c0 <= 'Z')) { return false } for i in 1..= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' if !ok { return false } } false } ///| fn normalize_slash_path(combined : String, leading_slash : Bool) -> String { let parts : Array[String] = [] for seg in combined.split("/") { let s = seg.to_owned() if s == "" || s == "." { continue } if s == ".." { if !parts.is_empty() && parts[parts.length() - 1] != ".." { ignore(parts.pop()) } else if !leading_slash { parts.push("..") } } else { parts.push(s) } } parts.join("/") } ///| /// Canonicalize a POSIX path or URL by normalizing dot segments in its path /// component while preserving any `scheme://authority` and `?query`. fn canonicalize_uri(uri : String) -> String { if uri == "" { return "" } let (path_part, query_part) = match uri.find("?") { Some(q) => (uri[:q].to_owned(), uri[q:].to_owned()) None => (uri, "") } match path_part.find("://") { Some(scheme_end) => { let after_scheme = scheme_end + 3 let rest = path_part[after_scheme:].to_owned() match rest.find("/") { Some(slash_idx) => { let origin = path_part[:after_scheme + slash_idx].to_owned() let p = normalize_slash_path(rest[slash_idx:].to_owned(), true) origin + "/" + p + query_part } None => path_part + query_part } } None => { let leading_slash = path_part.has_prefix("/") let p = normalize_slash_path(path_part, leading_slash) (if leading_slash { "/" + p } else { p }) + query_part } } } ///| /// Canonicalize a JSON pointer fragment (`#/...`) by percent-decoding and /// re-escaping segments so `#/components/schemas/My%20Type` and /// `#/components/schemas/My Type` map to the same cache key. fn canonicalize_fragment(fragment : String) -> String { if fragment == "" || fragment == "#" { return "#" } if !fragment.has_prefix("#/") { return fragment } let parts : Array[String] = [] for seg in fragment[2:].split("/") { let raw = seg.to_owned() let decoded = decode_fragment_segment(raw).unwrap_or(raw) parts.push(json_pointer_escape(decoded)) } "#/" + parts.join("/") } ///| /// Resolve a relative POSIX path or relative URL against `base_uri` per /// RFC 3986 §5.2 (preserving `scheme://authority`, handling `?query`-only refs, /// keeping query strings out of path normalization, and normalizing dot /// segments). fn resolve_relative_uri(base_uri : String, rel : String) -> String { if rel == "" { return canonicalize_uri(base_uri) } if has_uri_scheme(rel) { return canonicalize_uri(rel) } let (rel_path, rel_query) = match rel.find("?") { Some(q) => (rel[:q].to_owned(), rel[q:].to_owned()) None => (rel, "") } // Strip `?query` from `base_uri` before computing its directory/origin. let clean_base = match base_uri.find("?") { Some(q) => base_uri[:q].to_owned() None => base_uri } if rel_path == "" { return canonicalize_uri(clean_base) + rel_query } // Extract optional `scheme://authority` prefix from `clean_base`. let (scheme_prefix, origin_prefix, base_path) = match clean_base.find("://") { Some(scheme_end) => { let scheme = clean_base[:scheme_end].to_owned() let after_scheme = scheme_end + 3 let rest = clean_base[after_scheme:].to_owned() match rest.find("/") { Some(slash_idx) => ( scheme, clean_base[:after_scheme + slash_idx].to_owned(), rest[slash_idx:].to_owned(), ) None => (scheme, clean_base, "/") } } None => ("", "", clean_base) } // Protocol-relative `//host/path` for URLs; local POSIX `//...` normalizes to `/...`. if rel_path.has_prefix("//") { if scheme_prefix != "" { return canonicalize_uri("\{scheme_prefix}:\{rel_path}") + rel_query } let joined = normalize_slash_path(rel_path, true) return "/" + joined + rel_query } // Root-relative `/path`: keep `scheme://authority` when base is a URL. if rel_path.has_prefix("/") { let joined = normalize_slash_path(rel_path, true) if origin_prefix != "" { return origin_prefix + "/" + joined + rel_query } return "/" + joined + rel_query } let mut last_slash : Int32 = -1 for i in 0..= 0 { base_path[:last_slash + 1].to_owned() + rel_path } else { rel_path } let leading_slash = combined.has_prefix("/") || origin_prefix != "" let joined = normalize_slash_path(combined, leading_slash) if origin_prefix != "" { origin_prefix + "/" + joined + rel_query } else if leading_slash { "/" + joined + rel_query } else { joined + rel_query } } ///| /// Infer the target `#/components/
` and preferred component name from /// an external ref `(doc_uri, fragment)` and the context pointer where `$ref` /// appeared. fn infer_component_slot( doc_uri : String, fragment : String, context_section : String, ) -> (String, String) { // Prefer explicit `#/components/
/` when present. if fragment.has_prefix("#/components/") { let rest = fragment["#/components/".length():].to_owned() match rest.find("/") { Some(idx) => { let sec = rest[:idx].to_owned() let tail = rest[idx + 1:].to_owned() if !tail.contains("/") && tail != "" { let name = decode_fragment_segment(tail[:]).unwrap_or_else(fn() { json_pointer_unescape(tail[:]) }) return (sec, name) } } None => () } } // Extract last segment from fragment or filename stem from doc_uri. let base_name = if fragment.has_prefix("#/") { let segs : Array[String] = [] for s in fragment[2:].split("/") { segs.push(s.to_owned()) } if !segs.is_empty() { let last = segs[segs.length() - 1] decode_fragment_segment(last[:]).unwrap_or_else(fn() { json_pointer_unescape(last[:]) }) } else { "External" } } else { let segs : Array[String] = [] for s in doc_uri.split("/") { segs.push(s.to_owned()) } let file = if !segs.is_empty() { segs[segs.length() - 1] } else { "External" } match file.find(".") { Some(dot) if dot > 0 => file[:dot].to_owned() _ => file } } let section = if context_section != "" { context_section } else { "schemas" } (section, if base_name == "" { "External" } else { base_name }) } ///| fn parse_external_doc( text : String, uri : String, diags : Diagnostics, ) -> Node raise SpecError { let trimmed = text.trim() let (node, issues) = if uri.to_lower().has_suffix(".json") || trimmed.has_prefix("{") { parse_json_source(text) } else { parse_yaml_source(text) } for issue in issues { if issue.code.has_prefix("W-") { diags.warning(issue.code, issue.pointer, "\{uri}: \{issue.message}") } else { diags.error(issue.code, issue.pointer, "\{uri}: \{issue.message}") } } node } ///| priv struct Bundler { load_doc : (String) -> String raise SpecError diags : Diagnostics /// Canonical URI -> parsed root Node. doc_cache : Map[String, Node] /// `"uri#fragment"` -> internal `"#/components//"` pointer. bundled_refs : Map[String, String] /// section -> Array[(component_name, Node)] (new components bundled into root). sections : Map[String, Array[(String, Node)]] section_names : Map[String, Map[String, Unit]] } ///| /// Structural OpenAPI context while walking nodes for external `$ref` bundling. /// Prevents arbitrary user keys (e.g. a component or webhook named `"schemas"`) /// from misclassifying descendant `$ref` slots, and identifies /// `discriminator.mapping` objects whose string values are schema refs. priv enum RefContext { Root Components ComponentSection(String) PathsRoot PathItem Operation Section(String) Schema SchemaMap Discriminator DiscriminatorMapping } ///| fn RefContext::slot_section(self : RefContext) -> String { match self { Schema | SchemaMap | Discriminator | DiscriminatorMapping => "schemas" ComponentSection(s) | Section(s) => s PathsRoot | PathItem => "pathItems" _ => "schemas" } } ///| /// Keys whose values are verbatim user data (examples, defaults, enum/const /// literals) rather than OpenAPI schema/component structures — never descend /// into them for `$ref` or `discriminator.mapping` rewriting. fn is_literal_data_key(ctx : RefContext, key : String) -> Bool { if key.has_prefix("x-") { return true } match ctx { Schema => key is ("example" | "examples" | "default" | "const" | "enum") Section(_) | Operation | PathItem => key is ("example" | "value") _ => false } } ///| fn next_ref_context(ctx : RefContext, key : String) -> RefContext { match ctx { SchemaMap => Schema Schema => match key { "discriminator" => Discriminator "properties" | "patternProperties" | "dependentSchemas" | "$defs" => SchemaMap _ => Schema } Discriminator => if key == "mapping" { DiscriminatorMapping } else { Schema } DiscriminatorMapping => DiscriminatorMapping Root => match key { "components" => Components "paths" | "webhooks" => PathsRoot "$defs" => ComponentSection("schemas") _ => Root } Components => match key { "schemas" => ComponentSection("schemas") "parameters" => ComponentSection("parameters") "requestBodies" => ComponentSection("requestBodies") "responses" => ComponentSection("responses") "headers" => ComponentSection("headers") "securitySchemes" => ComponentSection("securitySchemes") "pathItems" => ComponentSection("pathItems") other => ComponentSection(other) } ComponentSection(sec) => match sec { "schemas" => Schema "pathItems" => PathItem other => Section(other) } PathsRoot => PathItem PathItem => match key { "parameters" => Section("parameters") "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace" | "query" => Operation _ => PathItem } Operation => match key { "parameters" => Section("parameters") "requestBody" => Section("requestBodies") "responses" => Section("responses") "callbacks" => PathsRoot _ => Operation } Section(sec) => match key { "properties" | "patternProperties" | "dependentSchemas" | "$defs" => SchemaMap "schema" | "items" | "additionalProperties" | "allOf" | "oneOf" | "anyOf" | "not" => Schema "headers" => Section("headers") "parameters" => Section("parameters") "requestBody" => Section("requestBodies") "responses" => Section("responses") _ => Section(sec) } } } ///| fn context_for_bundled_section(section : String) -> RefContext { match section { "schemas" => Schema "pathItems" => PathItem other => Section(other) } } ///| fn is_external_mapping_ref(val : String) -> Bool { if val == "#" || val.has_prefix("#/") { return false } if val.contains("#") || val.contains("/") { return true } let lower = val.to_lower() lower.has_suffix(".yaml") || lower.has_suffix(".yml") || lower.has_suffix(".json") } ///| fn Bundler::alloc_name( self : Bundler, section : String, preferred : String, ) -> String { let names = match self.section_names.get(section) { Some(m) => m None => { let m : Map[String, Unit] = Map([]) self.section_names[section] = m m } } if !names.contains(preferred) { names[preferred] = () return preferred } let mut idx : Int32 = 2 while true { let candidate = "\{preferred}_\{idx}" if !names.contains(candidate) { names[candidate] = () return candidate } idx += 1 } preferred } ///| fn Bundler::put_component( self : Bundler, section : String, name : String, node : Node, ) -> Unit { let list = match self.sections.get(section) { Some(arr) => arr None => { let arr : Array[(String, Node)] = [] self.sections[section] = arr arr } } list.push((name, node)) } ///| fn Bundler::load_uri(self : Bundler, uri : String) -> Node? { match self.doc_cache.get(uri) { Some(n) => Some(n) None => { let raw = (self.load_doc)(uri) catch { SpecError(msg) => { self.diags.error( "E-external-ref", "", "failed to load external ref document \"\{uri}\": \{msg}", ) return None } } let parsed = parse_external_doc(raw, uri, self.diags) catch { SpecError(msg) => { self.diags.error( "E-external-ref", "", "failed to parse external ref document \"\{uri}\": \{msg}", ) return None } } self.doc_cache[uri] = parsed Some(parsed) } } } ///| fn Bundler::bundle_external_target( self : Bundler, target_uri : String, fragment : String, context_section : String, ) -> String? { let canon_uri = canonicalize_uri(target_uri) let canon_frag = canonicalize_fragment(fragment) let cache_key = "\{canon_uri}\{canon_frag}" match self.bundled_refs.get(cache_key) { Some(internal_ref) => return Some(internal_ref) None => () } let ext_root = match self.load_uri(canon_uri) { Some(r) => r None => return None } let resolver = Resolver::new(ext_root, self.diags) let target_node = match resolver.resolve(fragment) { Some(n) => n None => return None } let (section, preferred) = infer_component_slot( canon_uri, fragment, context_section, ) let comp_name = self.alloc_name(section, preferred) let internal_ref = "#/components/\{section}/\{json_pointer_escape(comp_name)}" // Register before recursing to break mutual/self cycles immediately. self.bundled_refs[cache_key] = internal_ref let rewritten = self.rewrite_node( target_node, canon_uri, false, context_for_bundled_section(section), ) self.put_component(section, comp_name, rewritten) Some(internal_ref) } ///| fn Bundler::rewrite_ref_string( self : Bundler, ref_str : String, current_uri : String, is_root : Bool, slot_section : String, ) -> String? { let is_internal_to_current = ref_str == "#" || ref_str.has_prefix("#/") if !is_internal_to_current { let (doc_part, fragment) = split_external_ref(ref_str) let base = if current_uri == "__root__" { "" } else { current_uri } let resolved_uri = resolve_relative_uri(base, doc_part) self.bundle_external_target(resolved_uri, fragment, slot_section) } else if !is_root && current_uri != "" && current_uri != "__root__" { // Internal ref inside an external document must also be bundled into root! self.bundle_external_target(current_uri, ref_str, slot_section) } else { None } } ///| fn Bundler::rewrite_node( self : Bundler, node : Node, current_uri : String, is_root : Bool, ctx : RefContext, ) -> Node { match node { Array(items) => Array( items.map(item => self.rewrite_node(item, current_uri, is_root, ctx)), ) Object(obj) => { if ctx is DiscriminatorMapping { let out : Array[(String, Node)] = [] for entry in obj.entries { let (k, v) = entry match v { Str(ref_str) => { let is_internal = ref_str == "#" || ref_str.has_prefix("#/") let in_external = !is_root && current_uri != "" && current_uri != "__root__" let should_bundle = if is_internal { in_external } else { is_external_mapping_ref(ref_str) } if should_bundle { match self.rewrite_ref_string( ref_str, current_uri, is_root, "schemas", ) { Some(internal_ref) => out.push((k, Str(internal_ref))) None => out.push((k, v)) } } else if in_external && !ref_str.contains("#") && !ref_str.contains("/") { // Shorthand schema name inside an external document (e.g. `dog: Dog`): // if `ext_root` defines `#/components/schemas/`, bundle and rewrite it. let short_ref = "#/components/schemas/\{json_pointer_escape(ref_str)}" let exists_in_ext = match self.doc_cache.get(current_uri) { Some(ext_root) => match ext_root { Object(ro) => match ro.get("components") { Some(Object(co)) => match co.get("schemas") { Some(Object(so)) => so.get(ref_str) is Some(_) _ => false } _ => false } _ => false } None => false } if exists_in_ext { match self.bundle_external_target( current_uri, short_ref, "schemas", ) { Some(internal_ref) => out.push((k, Str(internal_ref))) None => out.push((k, v)) } } else { out.push((k, v)) } } else { out.push((k, v)) } } _ => out.push((k, v)) } } return Object({ entries: out, }) } match obj.get("$ref") { Some(Str(ref_str)) => match self.rewrite_ref_string( ref_str, current_uri, is_root, ctx.slot_section(), ) { Some(internal_ref) => { let new_entries : Array[(String, Node)] = [] for entry in obj.entries { let (k, v) = entry if k == "$ref" { new_entries.push(("$ref", Str(internal_ref))) } else if is_literal_data_key(ctx, k) { new_entries.push((k, v)) } else { new_entries.push( ( k, self.rewrite_node( v, current_uri, is_root, next_ref_context(ctx, k), ), ), ) } } return Object({ entries: new_entries, }) } None => if ref_str != "#" && !ref_str.has_prefix("#/") { return node } } _ => () } let out : Array[(String, Node)] = [] for entry in obj.entries { let (k, v) = entry if is_literal_data_key(ctx, k) { out.push((k, v)) continue } out.push( ( k, self.rewrite_node(v, current_uri, is_root, next_ref_context(ctx, k)), ), ) } Object({ entries: out, }) } _ => node } } ///| /// Bundle all external `$ref` targets reachable from `root` into internal /// `#/components/
/` entries using a caller-supplied sans-IO /// document loader `load_doc(resolved_uri) -> yaml_or_json_text`. pub fn bundle_external_refs( root : Node, base_uri~ : String = "", load_doc : (String) -> String raise SpecError, diags : Diagnostics, ) -> Node { let root_uri = if base_uri == "" { "__root__" } else { canonicalize_uri(base_uri) } let sections : Map[String, Array[(String, Node)]] = Map([]) let section_names : Map[String, Map[String, Unit]] = Map([]) let bundled_refs : Map[String, String] = Map([]) // Pre-seed existing component names (avoid collisions) and root component // cache keys (so external back-refs to the root doc reuse root definitions // instead of duplicating them as `Foo_2`). match root { Object(root_obj) => match root_obj.get("components") { Some(Object(comp_obj)) => for sec_entry in comp_obj.entries { let (sec_name, sec_val) = sec_entry match sec_val { Object(sec_items) => { let names : Map[String, Unit] = Map([]) for item in sec_items.entries { names[item.0] = () if base_uri != "" { let internal_ref = "#/components/\{sec_name}/\{json_pointer_escape(item.0)}" bundled_refs["\{root_uri}\{internal_ref}"] = internal_ref } } section_names[sec_name] = names } _ => () } } _ => () } _ => () } let bundler : Bundler = { load_doc, diags, doc_cache: Map([(root_uri, root)]), bundled_refs, sections, section_names, } let root_rewritten = bundler.rewrite_node(root, root_uri, true, Root) if bundler.sections.is_empty() { return root_rewritten } // Merge bundled components into root.components match root_rewritten { Object(root_obj) => { let existing_comp_entries : Array[(String, Node)] = match root_obj.get("components") { Some(Object(comp_obj)) => comp_obj.entries.copy() _ => [] } let merged_comps : Array[(String, Node)] = [] let seen_secs : Map[String, Unit] = Map([]) for entry in existing_comp_entries { let (sec_name, sec_val) = entry seen_secs[sec_name] = () match (sec_val, bundler.sections.get(sec_name)) { (Object(sec_obj), Some(added)) => { let combined = sec_obj.entries.copy() for a in added { combined.push(a) } merged_comps.push((sec_name, Object({ entries: combined, }))) } (Null, Some(added)) => merged_comps.push((sec_name, Object({ entries: added, }))) _ => merged_comps.push((sec_name, sec_val)) } } for sec_entry in bundler.sections { let (sec_name, added) = sec_entry if !seen_secs.contains(sec_name) { merged_comps.push((sec_name, Object({ entries: added, }))) } } let out_entries : Array[(String, Node)] = [] let mut had_components = false for entry in root_obj.entries { if entry.0 == "components" { had_components = true out_entries.push(("components", Object({ entries: merged_comps, }))) } else { out_entries.push(entry) } } if !had_components { out_entries.push(("components", Object({ entries: merged_comps, }))) } Object({ entries: out_entries, }) } _ => root_rewritten } }