import $Ref from "./ref.js"; import Pointer from "./pointer.js"; import * as url from "./util/url.js"; import { getSchemaBasePath, getSchemaId, getSchemaIdMode, usesDynamicIdScope } from "./util/schema-resources.js"; import { locateChild, type ReferenceLocation } from "./util/reference-location.js"; import type $Refs from "./refs.js"; import type $RefParser from "./index.js"; import type { ParserOptions } from "./index.js"; import type { JSONSchema } from "./index.js"; import type { BundleOptions } from "./options.js"; import { defaultBundleExcludedPathMatcher } from "./options.js"; export interface InventoryEntry { $ref: any; parent: any; key: any; pathFromRoot: any; depth: any; file: any; hash: any; value: any; circular: any; extended: any; external: any; nestedResource: boolean; indirections: any; scopeBase: string; dynamicIdScope: boolean; nestedIdScope: boolean; targetResourceBase: string; targetResourceId?: string; rootReference?: string; embeddedTargetPath?: string; targetOrigin?: TargetOrigin; preserveReference?: boolean; } // Only descendants reached through a resolved target move with that target. // Literal siblings at the same logical path stay at the authored reference. interface TargetOrigin { entry: InventoryEntry; path: string; parent: TargetOrigin | undefined; } interface CrawlContext { targetOrigin?: TargetOrigin; seen: Set; mergedTargets: Map; overlappingRefs: WeakSet; } /** * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that * only has *internal* references, not any *external* references. * This method mutates the JSON schema object, adding new references and re-mapping existing ones. * * @param parser * @param options */ function bundle = ParserOptions>( parser: $RefParser, options: O, ) { // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path); const rootScopeBase = parser.$refs._root$Ref.dynamicIdScope ? getSchemaBasePath(parser.$refs._root$Ref.path!, parser.schema, parser.$refs._root$Ref.legacyIdScope) : parser.$refs._root$Ref.path!; // Build an inventory of all $ref pointers in the JSON Schema const inventory: InventoryEntry[] = []; const embeddedResourcePaths = new Set([url.stripHash(parser.$refs._root$Ref.path!), url.stripHash(rootScopeBase)]); const context: CrawlContext = { seen: new Set(), mergedTargets: new Map(), overlappingRefs: new WeakSet() }; crawl( parser, "schema", { value: parser.schema, path: parser.$refs._root$Ref.path + "#", scopeBase: rootScopeBase, dynamicIdScope: parser.$refs._root$Ref.dynamicIdScope, legacyIdScope: parser.$refs._root$Ref.legacyIdScope, }, false, "#", 0, inventory, parser.$refs, options, embeddedResourcePaths, context, ); // Get the root schema's $id (if any) for qualifying refs inside sub-schemas with their own $id const rootId = getSchemaId(parser.schema, parser.$refs._root$Ref.legacyIdScope); // Remap all $ref pointers const generatedRefs = new Map(); embedSharedTargets(parser.schema, inventory, parser.$refs._root$Ref.legacyIdScope, context.overlappingRefs); remap(inventory, options, generatedRefs, rootId, rootScopeBase); finalizeReferences( parser.schema, inventory, generatedRefs, rootScopeBase, parser.$refs._root$Ref.dynamicIdScope, parser.$refs._root$Ref.legacyIdScope, (options.bundle || {}) as BundleOptions, ); } /** * Recursively crawls the given value, and inventories all JSON references. * * @param parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored. * @param key - The property key of `parent` to be crawled * @param location - The source document and URI scope of the property being crawled * @param pathFromRoot - The path of the property being crawled, from the schema root * @param indirections * @param inventory - An array of already-inventoried $ref pointers * @param $refs * @param options */ function crawl = ParserOptions>( parent: object | $RefParser, key: string | null, location: ReferenceLocation, nestedIdScope: boolean, pathFromRoot: string, indirections: number, inventory: InventoryEntry[], $refs: $Refs, options: O, embeddedResourcePaths: Set, context: CrawlContext, matcherAlreadyChecked = false, ) { const obj = key === null ? parent : parent[key as keyof typeof parent]; const bundleOptions = (options.bundle || {}) as BundleOptions; const isExcludedPath = bundleOptions.excludedPathMatcher || (() => false); if ( obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && (matcherAlreadyChecked || !isExcludedPath(pathFromRoot, obj)) ) { // Input schemas are normally JSON trees, but callers can pass pre-circular // JavaScript objects. Tracking identities keeps those cycles intact without // recursively walking them until the call stack overflows. It also avoids // repeatedly inventorying shared object instances. const visited = context.seen.has(obj); const isRef = $Ref.isAllowed$Ref(obj, options); if (visited && (!isRef || key === null)) { return; } context.seen.add(obj); if (isRef) { inventory$Ref( parent, key, location.path, location.scopeBase, location.dynamicIdScope, nestedIdScope, pathFromRoot, indirections, inventory, $refs, options, embeddedResourcePaths, context, ); if (visited || !$Ref.isExtended$Ref(obj)) { return; } } // Crawl the object in a specific order that's optimized for bundling. // This is important because it determines how `pathFromRoot` gets built, // which later determines which keys get dereferenced and which ones get remapped const keys = Object.keys(obj).sort((a, b) => { // Most people will expect references to be bundled into the the "definitions" property, // so we always crawl that property first, if it exists. if (a === "definitions" || a === "$defs") { return -1; } else if (b === "definitions" || b === "$defs") { return 1; } else { // Otherwise, crawl the keys based on their length. // This produces the shortest possible bundled references return a.length - b.length; } }) as (keyof typeof obj)[]; for (const key of keys) { if (isRef && key === "$ref") { continue; } const keyPathFromRoot = Pointer.join(pathFromRoot, key); const descriptor = Object.getOwnPropertyDescriptor(obj, key); if (descriptor?.get && isExcludedPath(keyPathFromRoot, undefined)) { continue; } const value = obj[key]; if (isExcludedPath(keyPathFromRoot, value)) { continue; } const child = locateChild($refs, location, key, value); const childHasSchemaIdentifier = child.dynamicIdScope && hasSchemaIdentifier(value, child.legacyIdScope); let childEmbeddedResourcePaths = embeddedResourcePaths; if (childHasSchemaIdentifier) { childEmbeddedResourcePaths = new Set(embeddedResourcePaths); childEmbeddedResourcePaths.add(url.stripHash(child.scopeBase)); } crawl( obj, key, child, nestedIdScope || childHasSchemaIdentifier, keyPathFromRoot, indirections, inventory, $refs, options, childEmbeddedResourcePaths, context, true, ); // We need to ensure that we have an object to work with here because we may be crawling // an `examples` schema and `value` may be nullish. if (value && typeof value === "object" && !Array.isArray(value)) { if ("$ref" in value) { bundleOptions?.onBundle?.(value["$ref"], obj[key], obj as any, key); } } } } } /** * Inventories the given JSON Reference (i.e. records detailed information about it so we can * optimize all $refs in the schema), and then crawls the resolved value. * * @param $refParent - The object that contains a JSON Reference as one of its keys * @param $refKey - The key in `$refParent` that is a JSON Reference * @param path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash * @param indirections - unknown * @param pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root * @param inventory - An array of already-inventoried $ref pointers * @param $refs * @param options */ function inventory$Ref = ParserOptions>( $refParent: any, $refKey: string | null, path: string, scopeBase: string, dynamicIdScope: boolean, nestedIdScope: boolean, pathFromRoot: string, indirections: number, inventory: InventoryEntry[], $refs: $Refs, options: O, embeddedResourcePaths: Set, context: CrawlContext, ) { const $ref = $refKey === null ? $refParent : $refParent[$refKey]; const shouldResolveOnCwd = $Ref.isExternal$Ref($ref) && options.dereference?.externalReferenceResolution === "root"; const resolutionBase = shouldResolveOnCwd ? url.cwd() : dynamicIdScope ? scopeBase : path; const $refPath = url.resolve(resolutionBase, $ref.$ref); const refFile = url.stripHash($refPath); const rootReference = refFile === $refs._root$Ref.path || $refs._aliases[refFile]?.value === $refs._root$Ref.value ? url.getHash($refPath) : undefined; const pointer = $refs._resolve($refPath, pathFromRoot, options); if (pointer === null) { return; } // Resolving a chain through an extended reference creates a fresh merged // object. Every occurrence of the same non-circular target must inventory // and update the instance that will actually be embedded in the bundle. let target = pointer.location!; if (target.child && !pointer.circular && !pointer.chainCircular) { const shared = context.mergedTargets.get($refPath); if (shared) { target = shared; } else { context.mergedTargets.set($refPath, target); } } const parsed = Pointer.parse(pathFromRoot); const depth = parsed.length; const file = url.stripHash(pointer.path); const hash = url.getHash(pointer.path); const alias = $refs._aliases[file]; const aliasIsInRootSchema = Boolean(alias && containsObject($refs._root$Ref.value, pointer.$ref.value)); const external = file !== $refs._root$Ref.path && !embeddedResourcePaths.has(file) && !aliasIsInRootSchema; const nestedResource = Boolean(alias) && pointer.$ref.value !== $refs._root$Ref.value; const targetResourceId = getSchemaId(pointer.$ref.value, pointer.$ref.legacyIdScope); const targetResourceBase = alias ? pointer.$ref.path! : pointer.$ref.dynamicIdScope ? getSchemaBasePath(pointer.$ref.path!, pointer.$ref.value, pointer.$ref.legacyIdScope) : pointer.$ref.path!; const extended = $Ref.isExtended$Ref($ref); indirections += pointer.indirections; const existingEntry = findInInventory(inventory, $refParent, $refKey); if (existingEntry) { // This $Ref has already been inventoried, so we don't need to process it again if (depth < existingEntry.depth || indirections < existingEntry.indirections) { removeFromInventory(inventory, existingEntry); } else { return; } } if (extended && options.dereference?.mergeKeys !== false) { preserveOverlappingRefs($ref, target.value, context.overlappingRefs); } const entry = { $ref, // The JSON Reference (e.g. {$ref: string}) parent: $refParent, // The object that contains this $ref pointer key: $refKey, // The key in `parent` that is the $ref pointer pathFromRoot, // The path to the $ref pointer, from the JSON Schema root depth, // How far from the JSON Schema root is this $ref pointer? file, // The file that the $ref pointer resolves to hash, // The hash within `file` that the $ref pointer resolves to value: target.value, // The resolved value of the $ref pointer circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself) extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref") external, // Does this $ref pointer point to a file other than the main JSON Schema file? nestedResource, // Does this $ref resolve to an embedded schema resource with its own $id? indirections, // The number of indirect references that were traversed to resolve the value scopeBase, // The active schema-resource base at the location of this $ref dynamicIdScope, // Whether this $ref uses nested JSON Schema $id scopes nestedIdScope, // Whether this $ref will remain inside a non-root $id scope after bundling targetResourceBase, // The canonical URI of the resource containing the target ...(targetResourceId === undefined ? {} : { targetResourceId }), ...(rootReference === undefined ? {} : { rootReference }), ...(context.targetOrigin && { targetOrigin: context.targetOrigin }), }; addToInventory(inventory, entry); // Recursively crawl the resolved value if (!existingEntry || external) { const resolvedScopeBase = pointer.$ref.dynamicIdScope ? pointer.scopeBase : pointer.$ref.path!; const resolvedNestedIdScope = nestedIdScope || (pointer.$ref.dynamicIdScope && hasSchemaIdentifier(pointer.value, pointer.legacyIdScope)); const resolvedEmbeddedResourcePaths = new Set(embeddedResourcePaths); if (pointer.value === pointer.$ref.value && hasSchemaIdentifier(pointer.$ref.value, pointer.$ref.legacyIdScope)) { resolvedEmbeddedResourcePaths.add(url.stripHash(pointer.$ref.path!)); resolvedEmbeddedResourcePaths.add(url.stripHash(resolvedScopeBase)); } crawl( target.value as S, null, target, resolvedNestedIdScope, pathFromRoot, indirections + 1, inventory, $refs, options, resolvedEmbeddedResourcePaths, { ...context, targetOrigin: { entry, path: pathFromRoot, parent: context.targetOrigin } }, ); } } /** * Deep merge selects keywords before dereferencing them. Inlining either side * of an overlapping $ref ahead of that merge would introduce the referenced * schema's keywords on the other side, even when its $ref was overridden. */ function preserveOverlappingRefs(source: object, target: unknown, refs: WeakSet) { const seen = new WeakMap>(); function visit(left: object, right: object) { let partners = seen.get(left); if (partners?.has(right)) { return; } if (!partners) { partners = new WeakSet(); seen.set(left, partners); } partners.add(right); for (const key of Object.keys(left)) { if (key === "$ref") { continue; } const a = Object.getOwnPropertyDescriptor(left, key)?.value; const b = Object.getOwnPropertyDescriptor(right, key)?.value; if (!a || !b || typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b)) { continue; } // Looking at data descriptors avoids evaluating getters on excluded paths. if (typeof Object.getOwnPropertyDescriptor(a, "$ref")?.value === "string") { refs.add(a); } if (typeof Object.getOwnPropertyDescriptor(b, "$ref")?.value === "string") { refs.add(b); } visit(a, b); } } if (target && typeof target === "object") { visit(source, target); } } /** * If every caller extends a target, inlining it several times would duplicate any * resource identifiers it contains. Inlining a caller inside its own target would * create a JavaScript cycle. Give these targets one unmodified definition. */ function embedSharedTargets( schema: any, inventory: InventoryEntry[], legacyIdScope: boolean, overlappingRefs: WeakSet, ) { if (!inventory.some((entry) => entry.external && (entry.extended || overlappingRefs.has(entry.$ref)))) { return; } const byTarget = new Map(); const extendedByPath = new Map(); for (const entry of inventory) { if (overlappingRefs.has(entry.$ref)) { entry.preserveReference = true; } if (entry.preserveReference || (entry.value && typeof entry.value === "object")) { if (entry.external && entry.extended) { extendedByPath.set(entry.file + entry.hash, entry); } const target = entry.value && typeof entry.value === "object" ? entry.value : entry.file + entry.hash; const group = byTarget.get(target); if (group) { group.push(entry); } else { byTarget.set(target, [entry]); } } } // A pointer into an overridden subtree also needs its unmodified source. const overriddenTargets = new Set(); for (const entry of inventory) { let hash = entry.hash as string; while (hash.includes("/")) { hash = hash.slice(0, hash.lastIndexOf("/")); const ancestor = extendedByPath.get(entry.file + hash); if (ancestor && Object.hasOwn(ancestor.$ref, Pointer.parse("#" + entry.hash.slice(hash.length))[0])) { overriddenTargets.add(ancestor.value); } } } const relocated = new Map(); const dynamicIdScope = usesDynamicIdScope(schema); const localResources = new Map>(); const definitionsToAdd: InventoryEntry[] = []; for (const entries of byTarget.values()) { const preserve = entries.some((entry) => entry.external && entry.preserveReference); if ( (!preserve && entries.length < 2 && !overriddenTargets.has(entries[0].value)) || entries.some((entry) => entry.external && !entry.extended && !entry.preserveReference) ) { continue; } const first = entries.find((entry) => entry.external); if (!first) { continue; } const paths = new Set(entries.map((entry) => entry.pathFromRoot)); const recursive = entries.some((entry) => findAncestorPath(entry.pathFromRoot, paths) !== undefined); if (!preserve && !recursive && !containsSchemaResource(first.value, legacyIdScope)) { continue; } const definition = createSharedDefinition(schema, first, legacyIdScope); definitionsToAdd.push(definition); const path = definition.pathFromRoot; for (const entry of entries) { relocated.set(entry, path); if (!dynamicIdScope) { // Generic JSON has no nested resource scopes on the next read. A // reference authored against this resource needs a document pointer. const hashes = localResources.get(entry.file) ?? new Map(); hashes.set(entry.hash, path); localResources.set(entry.file, hashes); } } } if (relocated.size) { // Children were inventoried through the original extended references. Their // file and scope remain the same, but their physical destination has moved. for (const entry of inventory) { const hashes = !entry.external && localResources.get(entry.file); if (hashes) { const hash = hashes.has(entry.hash) ? entry.hash : findAncestorPath(entry.hash, hashes); if (hash !== undefined) { entry.embeddedTargetPath = Pointer.join( hashes.get(hash)!, Pointer.parse("#" + entry.hash.slice(hash.length)), ); } } for (let origin = entry.targetOrigin; origin; origin = origin.parent) { const destination = relocated.get(origin.entry); if (destination !== undefined) { entry.pathFromRoot = destination + entry.pathFromRoot.slice(origin.path.length); entry.depth = Pointer.parse(entry.pathFromRoot).length; break; } } } for (const definition of definitionsToAdd) { addToInventory(inventory, definition); } } } function createSharedDefinition(schema: any, first: InventoryEntry, legacyIdScope: boolean): InventoryEntry { // OpenAPI and older JSON Schema dialects already define locations for named schemas. let owner = schema; let ownerPath = "#"; const olderDraft = legacyIdScope || (typeof schema.$schema === "string" && /draft-0[467]\//.test(schema.$schema)); let keyword = olderDraft || ("definitions" in owner && !("$defs" in owner)) ? "definitions" : "$defs"; if (typeof schema.openapi === "string") { owner = schema.components ??= {}; ownerPath = "#/components"; keyword = "schemas"; } else if (typeof schema.swagger === "string") { keyword = "definitions"; } // JSON arrays cannot serialize named properties. An extended reference is // itself an object, so it can carry the definition even in a bare array. if ( Array.isArray(owner) || !owner || typeof owner !== "object" || (owner[keyword] !== undefined && (!owner[keyword] || typeof owner[keyword] !== "object" || Array.isArray(owner[keyword]))) ) { owner = first.$ref; ownerPath = first.pathFromRoot; keyword = "$defs"; while (Object.hasOwn(owner, keyword)) { keyword = "_" + keyword; } } const definitions = (owner[keyword] ??= {}); const fileName = first.file.split("/").pop() || "resource"; // OpenAPI restricts component names to ASCII letters, digits, ".", "-" and "_". const name = keyword === "schemas" || typeof schema.swagger === "string" ? fileName.replace(/[^A-Za-z0-9._-]+/g, "_") : fileName; let key = name; let suffix = 2; while (Object.hasOwn(definitions, key)) { key = name + "-" + suffix++; } const path = Pointer.join(ownerPath, [keyword, key]); const ref = { $ref: first.file + first.hash }; Object.defineProperty(definitions, key, { value: ref, enumerable: true, configurable: true, writable: true }); return { ...first, $ref: ref, parent: definitions, key, pathFromRoot: path, depth: Pointer.parse(path).length, circular: false, extended: false, preserveReference: false, }; } function findAncestorPath(path: string, paths: ReadonlySet | ReadonlyMap) { let index = path.lastIndexOf("/"); while (index !== -1) { const ancestor = path.slice(0, index); if (paths.has(ancestor)) { return ancestor; } index = ancestor.lastIndexOf("/"); } return undefined; } function containsSchemaResource(value: object, legacyIdScope: boolean) { const seen = new Set(); function visit(node: any, legacy: boolean): boolean { if (!node || typeof node !== "object" || ArrayBuffer.isView(node) || seen.has(node)) { return false; } seen.add(node); legacy = getSchemaIdMode(node, legacy); return ( Boolean(getSchemaId(node, legacy)) || Object.keys(node).some((key) => { // Inspect data properties without evaluating getters on excluded paths. const descriptor = Object.getOwnPropertyDescriptor(node, key); return descriptor && "value" in descriptor && visit(descriptor.value, legacy); }) ); } return visit(value, legacyIdScope); } /** * Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema. * Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same * value are re-mapped to point to the first reference. * * @example: { * first: { $ref: somefile.json#/some/part }, * second: { $ref: somefile.json#/another/part }, * third: { $ref: somefile.json }, * fourth: { $ref: somefile.json#/some/part/sub/part } * } * * In this example, there are four references to the same file, but since the third reference points * to the ENTIRE file, that's the only one we need to dereference. The other three can just be * remapped to point inside the third one. * * On the other hand, if the third reference DIDN'T exist, then the first and second would both need * to be dereferenced, since they point to different parts of the file. The fourth reference does NOT * need to be dereferenced, because it can be remapped to point inside the first one. * * @param inventory */ function remap = ParserOptions>( inventory: InventoryEntry[], options: O, generatedRefs: Map, rootId?: string, rootScopeBase?: string, ) { // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them inventory.sort((a: InventoryEntry, b: InventoryEntry) => { if (a.file !== b.file) { // Group all the $refs that point to the same file return a.file < b.file ? -1 : +1; } else if (a.hash !== b.hash) { // Group all the $refs that point to the same part of the file return a.hash < b.hash ? -1 : +1; } else if (a.circular !== b.circular) { // If the $ref points to itself, then sort it higher than other $refs that point to this $ref return a.circular ? -1 : +1; } else if (a.extended !== b.extended) { // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value return a.extended ? +1 : -1; } else if (Boolean(a.preserveReference) !== Boolean(b.preserveReference)) { // Keep the authored $ref keyword for subsequent sibling merges. return a.preserveReference ? 1 : -1; } else if (a.indirections !== b.indirections) { // Sort direct references higher than indirect references return a.indirections - b.indirections; } else if (a.depth !== b.depth) { // Sort $refs by how close they are to the JSON Schema root return a.depth - b.depth; } else { // Determine how far each $ref is from the "definitions" property. // Most people will expect references to be bundled into the the "definitions" property if possible. const aDefinitionsIndex = Math.max( a.pathFromRoot.lastIndexOf("/definitions"), a.pathFromRoot.lastIndexOf("/$defs"), ); const bDefinitionsIndex = Math.max( b.pathFromRoot.lastIndexOf("/definitions"), b.pathFromRoot.lastIndexOf("/$defs"), ); if (aDefinitionsIndex !== bDefinitionsIndex) { // Give higher priority to the $ref that's closer to the "definitions" property return bDefinitionsIndex - aDefinitionsIndex; } else { // All else is equal, so use the shorter path, which will produce the shortest possible reference return a.pathFromRoot.length - b.pathFromRoot.length; } } }); let file, hash, pathFromRoot; // Sibling keys of the inlined $ref that other $refs are remapped to. An extended $ref is // inlined merged with its siblings, so those keys no longer hold the target's own values. let siblingKeys: Set | undefined; const recursiveEntries: InventoryEntry[] = []; const extendedEntries: InventoryEntry[] = []; function inline(entry: InventoryEntry) { if (entry.extended && !entry.circular) { extendedEntries.push(entry); } else { entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value, options); } } for (const entry of inventory) { // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot); const bundleOpts = (options.bundle || {}) as BundleOptions; if (entry.embeddedTargetPath !== undefined) { entry.$ref.$ref = entry.embeddedTargetPath; generatedRefs.set(entry.$ref, entry.embeddedTargetPath); } else if (!entry.external) { // This $ref already resolves to the main JSON Schema file. // When optimizeInternalRefs is false, preserve the original internal ref path // instead of rewriting it to the fully resolved hash. References to nested // resources must also retain their resource URI so that "#" does not point // at the document root instead. if ( entry.rootReference !== undefined && !entry.nestedIdScope && (bundleOpts.optimizeInternalRefs === false || !entry.nestedResource) ) { // An inlined file without its own $id now shares the root's scope. // Internalizing a reference back to that root is required even when // optimization is disabled; only collapsing its ref chain is optional. entry.$ref.$ref = bundleOpts.optimizeInternalRefs === false ? entry.rootReference : entry.hash; } else if (bundleOpts.optimizeInternalRefs !== false) { const targetResourceBase = url.stripHash(entry.targetResourceBase); const locationResourceBase = url.stripHash(entry.scopeBase); if (targetResourceBase !== locationResourceBase) { entry.$ref.$ref = referenceToResource(entry); } else if (!entry.nestedResource) { entry.$ref.$ref = entry.hash; } } } else if (entry.file === file && entry.hash === hash && !siblingKeys) { // This $ref points to the same value as the previous $ref, so remap it to the same path entry.$ref.$ref = qualifyPathFromRoot(entry, pathFromRoot, rootId, rootScopeBase); generatedRefs.set(entry.$ref, pathFromRoot); } else if (entry.file === file && entry.hash.indexOf(hash + "/") === 0) { // This $ref points to a sub-value of the previous $ref, so remap it beneath that path const tokens = Pointer.parse("#" + entry.hash.slice(hash.length)); if (pathFromRoot?.startsWith(entry.pathFromRoot + "/")) { // The ancestor was embedded beneath this sub-value. Redirecting this // location into that ancestor would remove the very path it points to. inline(entry); recursiveEntries.push(entry); } else if (siblingKeys?.has(tokens[0])) { // The previous $ref overrides this key with its own sibling, so the path beneath // it no longer holds the target's value. Inline the value here instead. inline(entry); if (containsObject(entry.value, entry.parent)) { recursiveEntries.push(entry); } } else { const subPath = Pointer.join(pathFromRoot, tokens); entry.$ref.$ref = qualifyPathFromRoot(entry, subPath, rootId, rootScopeBase); generatedRefs.set(entry.$ref, subPath); } } else { // This reference must be embedded at its own location. file = entry.file; hash = entry.hash; pathFromRoot = entry.pathFromRoot; siblingKeys = entry.extended ? new Set(Object.keys(entry.$ref).filter((key) => key !== "$ref")) : undefined; // This is the first $ref to point to this value, so dereference the value. // Any other $refs that point to the same value will point to this $ref instead inline(entry); if (entry.circular) { // This $ref points to itself entry.$ref.$ref = entry.pathFromRoot; generatedRefs.set(entry.$ref, entry.pathFromRoot); } } } // Deep merging copies property containers. Finish all child rewrites before // copying their containers, including inside another extended reference. for (const entry of extendedEntries.sort((a, b) => b.depth - a.depth)) { entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value, options); } for (const entry of recursiveEntries) { // Finish other external inlines before copying this subtree, so writes to // inventoried parents are retained in the recursive bundle as well. preserveRecursiveTargets(entry, inventory, generatedRefs, rootId, rootScopeBase); } // we want to ensure that any $refs that point to another $ref are remapped to point to the final value // let hadChange = true; // while (hadChange) { // hadChange = false; // for (const entry of inventory) { // if (entry.$ref && typeof entry.$ref === "object" && "$ref" in entry.$ref) { // const resolved = inventory.find((e: InventoryEntry) => e.pathFromRoot === entry.$ref.$ref); // if (resolved) { // const resolvedPointsToAnotherRef = // resolved.$ref && typeof resolved.$ref === "object" && "$ref" in resolved.$ref; // if (resolvedPointsToAnotherRef && entry.$ref.$ref !== resolved.$ref.$ref) { // // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot); // entry.$ref.$ref = resolved.$ref.$ref; // hadChange = true; // } // } // } // } // } } /** * Replaces cycles introduced by recursive external sub-paths with internal references. * Copying keeps source values distinct from extended refs that override their properties. */ function preserveRecursiveTargets( entry: InventoryEntry, inventory: InventoryEntry[], generatedRefs: Map, rootId?: string, rootScopeBase?: string, ) { const targets = new Set(inventory.map((candidate) => candidate.value)); targets.add(entry.$ref); const paths = new Map(); const activeTargets = new Map(); const parents = new Map(); const refScopes = new Map(); function copy(value: any, path: string, scope: InventoryEntry, legacyIdScope = false): any { if (!value || typeof value !== "object" || ArrayBuffer.isView(value)) { return value; } const recursivePath = activeTargets.get(value); if (recursivePath !== undefined) { // Only reference targets can be replaced with $refs. Intermediate maps // such as "properties" must remain literal objects in the bundle. const ref = { $ref: qualifyPathFromRoot(scope, recursivePath, rootId, rootScopeBase) }; generatedRefs.set(ref, recursivePath); return ref; } const parent = parents.get(value); if (parent && parent.targetCount === activeTargets.size) { // Preserve JavaScript object cycles that did not come from a $ref. return parent.copy; } legacyIdScope = getSchemaIdMode(value, legacyIdScope); if (hasSchemaIdentifier(value, legacyIdScope)) { scope = { ...scope, scopeBase: getSchemaBasePath(scope.scopeBase, value, legacyIdScope), dynamicIdScope: true, nestedIdScope: true, }; } if (targets.has(value)) { if (!paths.has(value)) { paths.set(value, path); } activeTargets.set(value, path); } if ($Ref.is$Ref(value)) { // Retain inventoried ref identities so subsequent remapping reaches all // their copied occurrences, including refs with sibling properties. refScopes.set(value, scope); activeTargets.delete(value); return value; } const result = Array.isArray(value) ? new Array(value.length) : {}; parents.set(value, { copy: result, targetCount: activeTargets.size }); for (const key of Object.keys(value)) { Object.defineProperty(result, key, { value: copy(value[key], Pointer.join(path, key), scope, legacyIdScope), writable: true, enumerable: true, configurable: true, }); } activeTargets.delete(value); if (parent) { parents.set(value, parent); } else { parents.delete(value); } return result; } entry.$ref = entry.parent[entry.key] = copy(entry.$ref, entry.pathFromRoot, { ...entry, scopeBase: entry.nestedIdScope ? entry.scopeBase : (rootScopeBase ?? entry.scopeBase), }); // An extended ref can move the unmodified source deeper into the bundle. // Prefer the closest source target so refs never traverse a generated $ref, // including when optimizeInternalRefs is disabled. const relocated = inventory .filter((candidate) => paths.has(candidate.value)) .sort((a, b) => b.hash.length - a.hash.length); for (const candidate of inventory) { if (!candidate.external || candidate.circular || !$Ref.is$Ref(candidate.$ref)) { continue; } const target = relocated.find( (target) => target.file === candidate.file && (target.hash === candidate.hash || candidate.hash.startsWith(target.hash + "/")), ); if (target) { const path = Pointer.join( paths.get(target.value)!, Pointer.parse("#" + candidate.hash.slice(target.hash.length)), ); candidate.$ref.$ref = qualifyPathFromRoot( refScopes.get(candidate.$ref) ?? candidate, path, rootId, rootScopeBase, ); generatedRefs.set(candidate.$ref, path); } } } /** * Index of the inventory, keyed by `$ref` parent and then by key, so that an already * inventoried $ref can be found without scanning the whole inventory. */ const inventoryIndexes = new WeakMap>>(); function addToInventory(inventory: InventoryEntry[], entry: InventoryEntry) { let index = inventoryIndexes.get(inventory); if (!index) { index = new Map(); inventoryIndexes.set(inventory, index); } let keys = index.get(entry.parent); if (!keys) { keys = new Map(); index.set(entry.parent, keys); } keys.set(entry.key, entry); inventory.push(entry); } function findInInventory(inventory: InventoryEntry[], $refParent: any, $refKey: any) { return inventoryIndexes.get(inventory)?.get($refParent)?.get($refKey); } function removeFromInventory(inventory: InventoryEntry[], entry: InventoryEntry) { const index = inventory.indexOf(entry); inventory.splice(index, 1); inventoryIndexes.get(inventory)?.get(entry.parent)?.delete(entry.key); } /** * Locate references in the finished bundle, after recursive targets and external * schemas have moved. Generated targets inside the same resource can use local * pointers; authored references retain their spelling when optimization is off. */ function finalizeReferences( schema: any, inventory: InventoryEntry[], generatedRefs: Map, rootScopeBase: string, dynamicIdScope: boolean, legacyIdScope: boolean, options: BundleOptions, ) { if ( inventory.length === 0 || (options.optimizeInternalRefs === false && (!dynamicIdScope || generatedRefs.size === 0)) ) { return; } interface Resource { value: object; path: string; } const trackedRefs = new Set([...inventory.map((entry) => entry.$ref), ...generatedRefs.keys()]); const references: { value: any; resource: Resource }[] = []; const resourceRoots = new Map(); const parents = new Set(); const isExcludedPath = options.excludedPathMatcher || (() => false); const visited = !options.excludedPathMatcher || options.excludedPathMatcher === defaultBundleExcludedPathMatcher ? new Map>() : undefined; function visit(value: any, path: string, scopeBase: string, legacyId: boolean, resource: Resource) { if (!value || typeof value !== "object" || ArrayBuffer.isView(value) || parents.has(value)) { return; } legacyId = getSchemaIdMode(value, legacyId); if (dynamicIdScope && path !== "#") { const nextBase = getSchemaBasePath(scopeBase, value, legacyId); // A plain-name fragment identifies a subschema within the current // resource. It does not establish a new JSON Pointer root. if (url.stripHash(nextBase) !== url.stripHash(scopeBase)) { resource = { value, path }; } scopeBase = nextBase; } if (visited) { const context = JSON.stringify([legacyId, scopeBase, resource.path]); const contexts = visited.get(value); if (contexts?.has(context)) { return; } if (contexts) { contexts.add(context); } else { visited.set(value, new Set([context])); } } parents.add(value); if (!resourceRoots.has(value)) { resourceRoots.set(value, resource.value); } else if (resourceRoots.get(value) !== resource.value) { resourceRoots.set(value, undefined); } if (trackedRefs.has(value) && typeof value.$ref === "string") { references.push({ value, resource }); } for (const key of Object.keys(value)) { const childPath = Pointer.join(path, key); const descriptor = Object.getOwnPropertyDescriptor(value, key); if (descriptor?.get && isExcludedPath(childPath, undefined)) { continue; } const child = value[key]; if (!isExcludedPath(childPath, child)) { visit(child, childPath, scopeBase, legacyId, resource); } } parents.delete(value); } if (!isExcludedPath("#", schema)) { visit(schema, "#", rootScopeBase, legacyIdScope, { value: schema, path: "#" }); } // A caller can share an object across resource scopes. Only mutate its ref // when every occurrence agrees on the rewrite. const rewrites = new Map(); function propose(value: any, ref: string) { if (!rewrites.has(value)) { rewrites.set(value, ref); } else if (rewrites.get(value) !== ref) { rewrites.set(value, undefined); } } function applyRewrites() { for (const [value, ref] of rewrites) { if (ref !== undefined && ref !== value.$ref) { value.$ref = ref; } } rewrites.clear(); } if (dynamicIdScope) { for (const { value, resource } of references) { const target = generatedRefs.get(value); if (target === undefined) { continue; } const insideResource = target === resource.path || target.startsWith(resource.path + "/"); propose( value, insideResource ? "#" + target.slice(resource.path.length) : value.$ref.startsWith("#") ? url.stripHash(rootScopeBase) + target : value.$ref, ); } applyRewrites(); } if (options.optimizeInternalRefs !== false) { for (const { value, resource } of references) { propose(value, resolvePathThroughRefs(resource.value, value.$ref, resourceRoots)); } applyRewrites(); } } /** * Walks a JSON pointer path through the schema. If any intermediate value * is a $ref, follows it and adjusts the path accordingly. * Returns the corrected path that doesn't traverse through any $ref. */ function resolvePathThroughRefs(schema: any, refPath: string, resourceRoots: Map): string { if (!isInternalPointer(refPath)) { return refPath; } const segments = Pointer.parse(refPath); let current = schema; const resolvedSegments: string[] = []; for (const seg of segments) { if ( current === null || current === undefined || typeof current !== "object" || resourceRoots.get(current) !== schema ) { // Do not follow a fragment reference after crossing into another resource. return refPath; } // If the next token is an own sibling of an extended $ref, the pointer // addresses that sibling directly and must not be rewritten through the // $ref target. Only follow the $ref when the literal object has no such key. if ( !Object.prototype.hasOwnProperty.call(current, seg) && "$ref" in current && typeof current.$ref === "string" && isInternalPointer(current.$ref) ) { // Follow the $ref and restart the path from its target const targetSegments = Pointer.parse(current.$ref); resolvedSegments.length = 0; resolvedSegments.push(...targetSegments); current = walkPath(schema, current.$ref, resourceRoots); if (current === null || current === undefined || typeof current !== "object") { return refPath; } } current = current[seg]; resolvedSegments.push(seg); } return Pointer.join("#", resolvedSegments); } /** * Walks a JSON pointer path through a schema object, returning the value at that path. */ function walkPath(schema: any, path: string, resourceRoots: Map): any { if (!isInternalPointer(path)) { return undefined; } const segments = Pointer.parse(path); let current = schema; for (const seg of segments) { if ( current === null || current === undefined || typeof current !== "object" || resourceRoots.get(current) !== schema ) { return undefined; } current = current[seg]; } return current; } function isInternalPointer(path: string): boolean { return path[0] === "#" && url.safeDecodeURIComponent(path.substring(1)).startsWith("/"); } /** * Qualifies a root-relative JSON Pointer when it is emitted inside a nested schema resource. * A fragment-only reference there would resolve against the nested resource rather than the * bundled document root. */ function qualifyPathFromRoot( entry: InventoryEntry, pathFromRoot: string, rootId?: string, rootScopeBase?: string, ): string { if (!entry.dynamicIdScope || !entry.nestedIdScope || !rootScopeBase) { return pathFromRoot; } // A fragment-only reference inside a nested schema resource resolves against // that resource's $id. Point back to the root resource explicitly instead. // Prefer the root's declared $id when it resolves correctly from this scope; // otherwise use the canonical root resource URI. let rootResource = rootScopeBase; if (rootId && url.stripHash(url.resolve(entry.scopeBase, rootId)) === url.stripHash(rootScopeBase)) { rootResource = rootId; } return url.stripHash(rootResource) + pathFromRoot; } function referenceToResource(entry: InventoryEntry): string { let resourceReference = url.stripHash(entry.targetResourceBase); if ( typeof entry.$ref.$ref === "string" && url.stripHash(url.resolve(entry.scopeBase, entry.$ref.$ref)) === resourceReference ) { return entry.$ref.$ref; } if ( entry.targetResourceId && url.stripHash(url.resolve(entry.scopeBase, entry.targetResourceId)) === resourceReference ) { resourceReference = entry.targetResourceId; } return entry.hash === "#" ? resourceReference : resourceReference + entry.hash; } function hasSchemaIdentifier(value: unknown, legacyIdScope = false): boolean { return getSchemaId(value, legacyIdScope) !== undefined; } function containsObject(root: unknown, target: unknown): boolean { if (!target || typeof target !== "object") { return false; } const seen = new Set(); const visit = (value: unknown): boolean => { if (value === target) { return true; } if (!value || typeof value !== "object" || ArrayBuffer.isView(value) || seen.has(value)) { return false; } seen.add(value); return Object.keys(value).some((key) => visit((value as Record)[key])); }; return visit(root); } export default bundle;