import path from "node:path"; import {describe, expect, it} from "vitest"; import uniform, {DefinitionProperty, Reference} from "@xyd-js/uniform"; // The JS impl directly — these pin the JS twin's behaviour whatever addon is // installed (the fixture matrix covers the dispatching entry point). import { collapseObjectsGroup, componentPagePath, deferencedOpenAPI, DISPLAY_NAME_KEY, explicitPagePath, groupByTagGroups, kebabCase, oapSchemaToReferences, objectsCollapsedOf, operationPagePath, TAG_GROUPS_KEY, uniformPluginXDocsSidebar, verbOf, type NavigationGroupEntry, } from "../src/impl-js"; // The package entry (what a consumer imports) — it re-exports a curated list. import * as packageEntry from "../index"; function fixture(name: string) { return path.join(__dirname, "..", "__fixtures__", name, "input.yaml"); } function row(rows: DefinitionProperty[] | undefined, name: string): DefinitionProperty { const found = rows?.find(p => p.name === name); if (!found) { throw new Error(`no row ${name} in ${JSON.stringify(rows?.map(p => p.name))}`); } return found; } function metaValue(p: DefinitionProperty, name: string) { return p.meta?.find(m => m.name === name)?.value; } function byCanonical(refs: Reference[], canonical: string): Reference { const found = refs.find(r => r.canonical === canonical); if (!found) { throw new Error(`no reference ${canonical}`); } return found; } describe("docs metadata (JS impl)", () => { it("a constant's value: single-value enums and `const` carry the `const` meta", async () => { const doc = await deferencedOpenAPI(fixture("9.schema-links")); const refs = oapSchemaToReferences(doc!); const rows = byCanonical(refs, "objects/Widget").definitions[0].properties; const object = row(rows, "object"); expect(object.type).toBe("$$enum"); expect(metaValue(object, "const")).toBe("widget"); expect(metaValue(object, "enum-type")).toBe("string"); expect(object.properties?.map(p => p.name)).toEqual(["widget"]); const kind = row(rows, "kind"); expect(kind.type).toBe("$$enum"); expect(metaValue(kind, "const")).toBe("standard"); expect(kind.properties?.map(p => p.name)).toEqual(["standard"]); const status = row(rows, "status"); expect(status.type).toBe("$$enum"); expect(metaValue(status, "const")).toBeUndefined(); expect(status.properties?.length).toBe(2); }); it("allOf: [$ref ] + description is a scalar row, never a parent with a nameless child", async () => { const doc = await deferencedOpenAPI(fixture("9.schema-links")); const refs = oapSchemaToReferences(doc!); const rows = byCanonical(refs, "objects/Widget").definitions[0].properties; const id = row(rows, "id"); expect(id.type).toBe("string"); expect(id.description).toBe("Unique identifier for the widget."); expect(id.properties).toEqual([]); expect(metaValue(id, "required")).toBe("true"); expect(metaValue(id, "example")).toBe("0d4f1e2a-6b2c-4f33-9d7e-1a2b3c4d5e6f"); const color = row(rows, "color"); expect(color.type).toBe("$$enum"); expect(color.properties?.map(p => p.name)).toEqual(["red", "green", "blue"]); expect(color.ofProperty?.type).toBe("string"); expect(metaValue(color, "enum-type")).toBe("string"); // A typed wrapper (`type: string`) around the enum is the same enum row. const shade = row(rows, "shade"); expect(shade.type).toBe("$$enum"); expect(shade.description).toBe("The shade of the widget."); expect(shade.properties?.map(p => p.name)).toEqual(["red", "green", "blue"]); expect(shade.ofProperty?.type).toBe("string"); expect(shade.symbolDef?.canonical).toBe("objects/Color"); }); it("allOf: a composed member keeps its rows whatever its position among the members", async () => { const doc = await deferencedOpenAPI(fixture("9.schema-links")); const refs = oapSchemaToReferences(doc!); const rows = byCanonical(refs, "objects/Widget").definitions[0].properties; // `allOf: [{type: object, properties: {label}}, $ref Assembly]` where // Assembly is itself `allOf: [$ref AssemblyBase, {properties: {sku}}]`. const assembly = row(rows, "assembly"); expect(assembly.type).toBe("object"); expect(assembly.description).toBe("How the widget is assembled."); expect(assembly.properties?.map(p => p.name)).toEqual(["label", "id", "sku"]); expect(assembly.symbolDef?.canonical).toBe("objects/Assembly"); // The other order, on an inline document (an inline `allOf` member has // no `properties` key of its own either, so it takes the same fold // path as a `$ref` to a composition): the composed member's rows // first, the wrapper's own after them. const composed = () => ({ allOf: [ {type: "object", properties: {id: {type: "string"}}}, {type: "object", properties: {sku: {type: "string"}}}, ], }); const inline: any = { openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, paths: {}, components: { schemas: { Widget: { type: "object", properties: { composed_first: {allOf: [composed(), {type: "object", properties: {name: {type: "string"}}}]}, overlap: {allOf: [{type: "object", properties: {id: {type: "string", description: "the wrapper's id"}}}, composed()]}, }, }, }, }, }; const inlineRows = byCanonical(oapSchemaToReferences(inline), "objects/Widget").definitions[0].properties; expect(row(inlineRows, "composed_first").properties?.map(p => p.name)).toEqual(["id", "sku", "name"]); // A row both sides declare is merged by name, the description kept. const overlap = row(inlineRows, "overlap"); expect(overlap.properties?.map(p => p.name)).toEqual(["id", "sku"]); expect(row(overlap.properties, "id").description).toBe("the wrapper's id"); }); it("nested properties that are a component schema link to its page", async () => { const doc = await deferencedOpenAPI(fixture("9.schema-links")); const refs = oapSchemaToReferences(doc!); const widget = byCanonical(refs, "objects/Widget").definitions[0].properties; expect(row(widget, "definition").symbolDef).toEqual({ id: "#/components/schemas/WidgetDefinition", canonical: "objects/WidgetDefinition", label: "WidgetDefinition", }); // Through allOf: [$ref] as well. expect(row(widget, "id").symbolDef).toEqual({ id: "#/components/schemas/WidgetId", canonical: "objects/WidgetId", label: "WidgetId", }); // An array of a component links to the component, on the row and its items. const parts = row(widget, "parts"); expect(parts.symbolDef?.canonical).toBe("objects/Part"); expect(parts.ofProperty?.symbolDef?.canonical).toBe("objects/Part"); // Inline schemas do not link. expect(row(widget, "created_at").symbolDef).toBeUndefined(); expect(row(widget, "status").symbolDef).toBeUndefined(); // A request body's described allOf: [$ref] member and a parameter's $ref schema. const create = byCanonical(refs, "createWidget"); const body = create.definitions.find(d => d.title === "Request body")!.variants![0].properties; expect(row(body, "definition").symbolDef?.canonical).toBe("objects/WidgetDefinition"); const get = byCanonical(refs, "getWidget"); const params = get.definitions.find(d => d.title === "Path parameters")!.properties; expect(row(params, "widgetId").symbolDef?.canonical).toBe("objects/WidgetId"); }); it("x-docs on component schemas: name, group and hidden outside sidebar mode", async () => { const doc = await deferencedOpenAPI(fixture("5.xdocs.objects")); const refs = uniform(oapSchemaToReferences(doc!), {plugins: [uniformPluginXDocsSidebar]}).references; // The default objects layout (`grouped`): every object page in ONE // top-level "Objects" group after the operations — the page without a // resource group first, then one sub-group per resource group in the // order the groups appear above (`widgets` has operations, `parts` // has none, so it follows). expect(refs.map(r => r.title)).toEqual([ "List widgets", "Create a widget", "Retrieve widget", "PartBase", "The widget object", "The part object", ]); const widget = byCanonical(refs, "objects/Widget"); expect(widget.title).toBe("The widget object"); expect(widget.context?.group).toEqual(["Objects", "widgets"]); const part = byCanonical(refs, "objects/Part"); expect(part.context?.group).toEqual(["Objects", "parts"]); expect(byCanonical(refs, "objects/PartBase").context?.group).toEqual(["Objects"]); // An operation's own `x-docs.group` is never nested. expect(byCanonical(refs, "listWidgets").context?.group).toEqual(["widgets"]); // hidden: the operation and the three schemas are gone. expect(refs.some(r => r.canonical === "health")).toBe(false); expect(refs.some(r => r.canonical === "objects/WidgetList")).toBe(false); expect(refs.some(r => r.canonical === "objects/Error")).toBe(false); expect(refs.some(r => r.canonical === "objects/Tag")).toBe(false); // A link to a hidden schema keeps its id and loses its canonical — on // the object page and on every endpoint that embeds the schema. const tags = row(widget.definitions[0].properties, "tags"); expect(tags.symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); expect(tags.ofProperty?.symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); const create = byCanonical(refs, "createWidget"); const body = create.definitions.find(d => d.title === "Request body")!.variants![0].properties; expect(row(body, "tags").symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); // A link to a page that exists stays whole: listWidgets → WidgetList // (hidden, inlined) → data: array of Widget. const list = byCanonical(refs, "listWidgets"); const links: string[] = []; const walk = (p: DefinitionProperty | undefined) => { if (!p) return; if (typeof p.symbolDef?.canonical === "string") links.push(p.symbolDef.canonical); p.properties?.forEach(walk); walk(p.ofProperty); }; for (const d of list.definitions) { d.properties?.forEach(walk); d.variants?.forEach(v => v.properties?.forEach(walk)); } expect(links).toContain("objects/Widget"); expect(links).not.toContain("objects/Tag"); // The response ROOT links to the hidden envelope: the variant's own // symbolDef loses its canonical too, and keeps its id and label (the // envelope's constant `object` value). const root = list.definitions.find(d => d.title === "Response")!.variants![0].symbolDef; expect(root).toEqual({id: "#/components/schemas/WidgetList", label: "list"}); }); it("the objectsGroup option names the top-level group and the sub-group", async () => { const doc = await deferencedOpenAPI(fixture("5.xdocs.objects")); const refs = uniform(oapSchemaToReferences(doc!, {objectsGroup: "Types"}), {plugins: [uniformPluginXDocsSidebar]}).references; expect(byCanonical(refs, "objects/Widget").context?.group).toEqual(["Types", "widgets"]); expect(byCanonical(refs, "objects/Part").context?.group).toEqual(["Types", "parts"]); expect(byCanonical(refs, "objects/PartBase").context?.group).toEqual(["Types"]); expect(byCanonical(refs, "listWidgets").context?.group).toEqual(["widgets"]); // Under the per-area layout the renamed group is the sub-group. const perArea = uniform(oapSchemaToReferences(doc!, {objectsGroup: "Types", objectsLayout: "per-area"}), {plugins: [uniformPluginXDocsSidebar]}).references; expect(byCanonical(perArea, "objects/Widget").context?.group).toEqual(["widgets", "Types"]); expect(byCanonical(perArea, "objects/PartBase").context?.group).toEqual(["Types"]); // An empty name means the default. const plain = uniform(oapSchemaToReferences(doc!, {objectsGroup: ""}), {plugins: [uniformPluginXDocsSidebar]}).references; expect(byCanonical(plain, "objects/Widget").context?.group).toEqual(["Objects", "widgets"]); }); it("objectsLayout: per-area nests an object page under its resource group's Objects sub-group", async () => { const doc = await deferencedOpenAPI(fixture("5.xdocs.objects")); const refs = uniform(oapSchemaToReferences(doc!, {objectsLayout: "per-area"}), {plugins: [uniformPluginXDocsSidebar]}).references; // The object pages keep the schema order; the navigation lists each // sub-group after its group's operations. expect(refs.map(r => r.title)).toEqual([ "List widgets", "Create a widget", "Retrieve widget", "The widget object", "The part object", "PartBase", ]); expect(byCanonical(refs, "objects/Widget").context?.group).toEqual(["widgets", "Objects"]); expect(byCanonical(refs, "objects/Part").context?.group).toEqual(["parts", "Objects"]); expect(byCanonical(refs, "objects/PartBase").context?.group).toEqual(["Objects"]); expect(byCanonical(refs, "listWidgets").context?.group).toEqual(["widgets"]); // An unknown layout name means the default. const fallback = uniform(oapSchemaToReferences(doc!, {objectsLayout: "sideways" as any}), {plugins: [uniformPluginXDocsSidebar]}).references; expect(byCanonical(fallback, "objects/Widget").context?.group).toEqual(["Objects", "widgets"]); }); it("grouped layout: the Objects group is last, its pages ordered by the groups above", async () => { const doc = await deferencedOpenAPI(fixture("11.objects-layouts")); const refs = uniform(oapSchemaToReferences(doc!), {plugins: [uniformPluginXDocsSidebar]}).references; // Operations in tag order (declared `parts`, `widgets`; the undeclared // `assemblies`; the untagged `getStatus`), then EVERY object page: the // two without a resource group first (schema order), then the groups // in the order they appear above — `parts`, `widgets`, `assemblies` — // then `fasteners`, which has no operations. expect(refs.map(r => r.canonical)).toEqual([ "listParts", "listWidgets", "listAudit", "createAssembly", "getStatus", "objects/Status", "objects/Address", "objects/Part", "objects/Widget", "objects/Assembly", "objects/Fastener", ]); expect(refs.map(r => r.context?.group)).toEqual([ ["parts"], ["widgets"], ["audit"], ["assemblies"], [""], ["Objects"], ["Objects"], ["Objects", "parts"], ["Objects", "widgets"], ["Objects", "assemblies"], ["Objects", "fasteners"], ]); // The hidden schemas have no page. expect(refs.some(r => r.canonical === "objects/WidgetList")).toBe(false); expect(refs.some(r => r.canonical === "objects/Error")).toBe(false); }); it("object pages sort after every operation, even one tagged with the objects group's name", () => { const doc: any = { openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, tags: [{name: "Objects"}, {name: "widgets"}], paths: { "/objects": {get: {operationId: "listObjects", summary: "List objects", tags: ["Objects"], responses: {"200": {description: "ok"}}}}, "/widgets": {get: {operationId: "listWidgets", summary: "List widgets", tags: ["widgets"], responses: {"200": {description: "ok"}}}}, }, components: {schemas: {Widget: {type: "object", properties: {id: {type: "string"}}}}}, }; const refs = oapSchemaToReferences(doc); expect(refs.map(r => r.canonical)).toEqual(["listObjects", "listWidgets", "objects/Widget"]); }); it("schema links carry the schema's label: its constant `object` value, else its name", async () => { const doc = await deferencedOpenAPI(fixture("10.schema-labels")); const refs = oapSchemaToReferences(doc!); // The component pages' own links. const widget = byCanonical(refs, "objects/Widget"); expect(widget.definitions[0].symbolDef).toEqual({ id: "#/components/schemas/Widget", canonical: "objects/Widget", label: "widget", }); expect(byCanonical(refs, "objects/Material").definitions[0].symbolDef?.label).toBe("Material"); expect(byCanonical(refs, "objects/Part").definitions[0].symbolDef?.label).toBe("part"); expect(byCanonical(refs, "objects/Assembly").definitions[0].symbolDef?.label).toBe("assembly"); // Nested rows: a schema without an `object` property, a multi-value // `object` enum (not a constant), a `const`, a tag on an allOf member. const rows = widget.definitions[0].properties; expect(row(rows, "material").symbolDef?.label).toBe("Material"); expect(row(rows, "shape").symbolDef?.label).toBe("Shape"); expect(row(rows, "assembly").symbolDef?.label).toBe("assembly"); const parts = row(rows, "parts"); expect(parts.symbolDef?.label).toBe("part"); expect(parts.ofProperty?.symbolDef?.label).toBe("part"); expect(row(rows, "id").symbolDef).toBeUndefined(); // An array of widgets: the row and its items. const list = byCanonical(refs, "objects/WidgetList"); expect(list.definitions[0].symbolDef?.label).toBe("list"); const data = row(list.definitions[0].properties, "data"); expect(data.type).toBe("$$array"); expect(data.symbolDef?.label).toBe("widget"); expect(data.ofProperty?.symbolDef?.label).toBe("widget"); // A nullable widget (allOf + nullable) and a union with a null branch. const slot = byCanonical(refs, "objects/Slot").definitions[0].properties; const nullable = row(slot, "widget"); expect(nullable.type).toBe("object"); expect(metaValue(nullable, "nullable")).toBe("true"); expect(nullable.symbolDef?.label).toBe("widget"); const spare = row(slot, "spare"); expect(spare.type).toBe("$$union"); expect(spare.symbolDef).toBeUndefined(); expect(spare.properties?.[0].symbolDef?.label).toBe("widget"); expect(spare.properties?.[1].symbolDef).toBeUndefined(); // The request/response roots: a `$ref` root, an array root (its // items'), a request body; an inline root has no link. const response = (canonical: string, index = 0) => byCanonical(refs, canonical).definitions.find(d => d.title === "Response")!.variants![index].symbolDef; expect(response("getWidget")).toEqual({ id: "#/components/schemas/Widget", canonical: "objects/Widget", label: "widget", }); expect(response("listWidgets")?.label).toBe("list"); expect(response("listMaterials")?.label).toBe("Material"); expect(response("getSlot", 1)).toBeUndefined(); const body = byCanonical(refs, "createWidget").definitions.find(d => d.title === "Request body")!.variants![0]; expect(body.symbolDef?.label).toBe("widget"); }); it("an x-docs.sidebar: links follow the listed page, a listed composition reads its own x-docs", () => { // The shape a dereferenced document has: ONE object per component, // shared between `components.schemas` and every place that used it. const Tag: any = {type: "object", properties: {name: {type: "string"}}}; const Widget: any = { "x-docs": {name: "The widget object"}, type: "object", properties: {id: {type: "string"}, tags: {type: "array", items: Tag}}, }; const WidgetList: any = {type: "object", properties: {data: {type: "array", items: Widget}}}; const PartBase: any = {type: "object", properties: {id: {type: "string"}}}; const doc: any = { openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, paths: { "/widgets": { get: { operationId: "listWidgets", summary: "List widgets", responses: {"200": {description: "ok", content: {"application/json": {schema: WidgetList}}}}, }, }, }, components: { schemas: { Widget, WidgetList, Tag, PartBase, Bundle: { "x-docs": {name: "The bundle object"}, allOf: [PartBase, {type: "object", properties: {count: {type: "integer"}}}], }, Kit: {allOf: [PartBase]}, }, }, "x-docs": { sidebar: [{ group: "Reference", pages: [ {type: "endpoint", key: "listWidgets"}, {type: "object", key: "Widget", path: "the-widget"}, {type: "object", key: "Bundle"}, {type: "object", key: "Kit"}, ], }], }, }; const refs = uniform(oapSchemaToReferences(doc), {plugins: [uniformPluginXDocsSidebar]}).references; // The composition's own x-docs is read (not only a member's); one // without any x-docs keeps its page and its default title. expect(refs.map(r => r.title)).toEqual(["List widgets", "The widget object", "The bundle object", "Kit"]); const widget = refs[1]; expect(widget.canonical).not.toBe("objects/Widget"); // listWidgets → data: array of Widget follows the moved page, on the // row and on its items. const data = row(refs[0].definitions[0].variants![0].properties, "data"); expect(data.symbolDef?.canonical).toBe(widget.canonical); expect(data.ofProperty?.symbolDef?.canonical).toBe(widget.canonical); // Widget.tags → Tag is not listed: no page, so no canonical. const tags = row(widget.definitions[0].properties, "tags"); expect(tags.symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); expect(tags.ofProperty?.symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); }); it("regions mode (one page at a time): the links follow the document, not the one-page list", async () => { // A generated page converts ONE region, then runs the plugin: the // sidebar pass is not its business, but its links still have to land // on pages that exist — hidden schemas have none. const doc = await deferencedOpenAPI(fixture("5.xdocs.objects")); const page = (region: string) => uniform(oapSchemaToReferences(doc!, {regions: [region]}), {plugins: [uniformPluginXDocsSidebar]}).references; const widget = page("/components/schemas/Widget"); expect(widget.map(r => r.canonical)).toEqual(["objects/Widget"]); const tags = row(widget[0].definitions[0].properties, "tags"); expect(tags.symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); expect(tags.ofProperty?.symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); const list = page("GET /widgets"); expect(list.map(r => r.canonical)).toEqual(["listWidgets"]); const data = row(list[0].definitions[0].variants![0].properties, "data"); expect(data.symbolDef?.canonical).toBe("objects/Widget"); expect(data.ofProperty?.symbolDef?.canonical).toBe("objects/Widget"); const create = page("POST /widgets"); const body = create[0].definitions.find(d => d.title === "Request body")!.variants![0].properties; expect(row(body, "tags").symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); }); it("regions mode under an x-docs.sidebar: the links follow the listed page", () => { const Tag: any = {type: "object", properties: {name: {type: "string"}}}; const Widget: any = { "x-docs": {name: "The widget object"}, type: "object", properties: {id: {type: "string"}, tags: {type: "array", items: Tag}}, }; const WidgetList: any = {type: "object", properties: {data: {type: "array", items: Widget}}}; const doc: any = { openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, paths: { "/widgets": { get: { operationId: "listWidgets", summary: "List widgets", responses: {"200": {description: "ok", content: {"application/json": {schema: WidgetList}}}}, }, }, }, components: {schemas: {Widget, WidgetList, Tag}}, "x-docs": { sidebar: [{ group: "Reference", pages: [ {type: "endpoint", key: "listWidgets"}, {type: "object", key: "Widget", path: "the-widget"}, ], }], }, }; // The whole-document pass says where the page went. const whole = uniform(oapSchemaToReferences(doc), {plugins: [uniformPluginXDocsSidebar]}).references; const widgetCanonical = whole[1].canonical; expect(widgetCanonical).not.toBe("objects/Widget"); const page = (region: string) => uniform(oapSchemaToReferences(doc, {regions: [region]}), {plugins: [uniformPluginXDocsSidebar]}).references; const data = row(page("GET /widgets")[0].definitions[0].variants![0].properties, "data"); expect(data.symbolDef?.canonical).toBe(widgetCanonical); expect(data.ofProperty?.symbolDef?.canonical).toBe(widgetCanonical); // Tag is not listed: no page, so no canonical. const tags = row(page("/components/schemas/Widget")[0].definitions[0].properties, "tags"); expect(tags.symbolDef).toEqual({id: "#/components/schemas/Tag", label: "Tag"}); }); it("x-docs.path names a page's path; the links follow, the grouping does not change", () => { const Tag: any = {type: "object", properties: {name: {type: "string"}}}; const Widget: any = { "x-docs": {name: "The widget object", group: "widgets", path: "widgets/object"}, type: "object", properties: {id: {type: "string"}, tags: {type: "array", items: Tag}}, }; const WidgetList: any = {type: "object", properties: {data: {type: "array", items: Widget}}}; const doc: any = { openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, tags: [{name: "widgets"}], paths: { "/widgets": { get: { operationId: "listWidgets", summary: "List widgets", tags: ["widgets"], "x-docs": {path: "/widgets/list/"}, responses: {"200": {description: "ok", content: {"application/json": {schema: WidgetList}}}}, }, }, }, components: {schemas: {Widget, WidgetList, Tag}}, }; const refs = uniform(oapSchemaToReferences(doc), {plugins: [uniformPluginXDocsSidebar]}).references; // The grouped layout's order: the pages without a resource group, then // the `widgets` sub-group — the path does not move the page. expect(refs.map(r => r.canonical)).toEqual(["widgets/list", "objects/WidgetList", "objects/Tag", "widgets/object"]); expect(byCanonical(refs, "widgets/list").context?.group).toEqual(["widgets"]); expect(byCanonical(refs, "widgets/object").context?.group).toEqual(["Objects", "widgets"]); // listWidgets → data: array of Widget follows the explicit path; so does // the page's own link. const data = row(refs[0].definitions[0].variants![0].properties, "data"); expect(data.symbolDef?.canonical).toBe("widgets/object"); expect(data.ofProperty?.symbolDef?.canonical).toBe("widgets/object"); expect(byCanonical(refs, "widgets/object").definitions[0].symbolDef?.canonical).toBe("widgets/object"); // Regions mode reads the same path from the document. const page = uniform(oapSchemaToReferences(doc, {regions: ["GET /widgets"]}), {plugins: [uniformPluginXDocsSidebar]}).references; expect(page[0].canonical).toBe("widgets/list"); expect(row(page[0].definitions[0].variants![0].properties, "data").symbolDef?.canonical).toBe("widgets/object"); }); it("two pages at one path are an error naming both", () => { const operation = (operationId: string, summary: string, xDocs?: any) => ({ operationId, summary, tags: ["widgets"], ...(xDocs ? {"x-docs": xDocs} : {}), responses: {"200": {description: "ok"}}, }); const doc = (a: any, b: any): any => ({ openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, paths: {"/widgets": {get: a}, "/widgets/all": {get: b}}, components: {schemas: {}}, }); const run = (d: any, options?: any) => () => uniform(oapSchemaToReferences(d, options), {plugins: [uniformPluginXDocsSidebar]}); // Two equal `x-docs.path`s. const explicit = doc( operation("listWidgets", "List widgets", {path: "widgets/list"}), operation("listAllWidgets", "List all widgets", {path: "widgets/list"}), ); expect(run(explicit)).toThrow(/two pages share the path "widgets\/list": GET \/widgets \("List widgets"\) and GET \/widgets\/all \("List all widgets"\)/); // Two summaries that derive the same canonical under `title`. const derived = doc(operation("listWidgets", "List widgets"), operation("listAllWidgets", "List all widgets")); expect(run(derived, {operationPaths: "title"})).toThrow(/"widgets\/list".*GET \/widgets\/all/); // The default mode: distinct operationIds, no collision. expect(run(derived)().references.map(r => r.canonical)).toEqual(["listWidgets", "listAllWidgets"]); // An `x-docs.path` on one of them resolves it. const resolved = doc(operation("listWidgets", "List widgets"), operation("listAllWidgets", "List all widgets", {path: "widgets/list-all"})); expect(run(resolved, {operationPaths: "title"})().references.map(r => r.canonical)).toEqual(["widgets/list", "widgets/list-all"]); }); it("operationPaths: title derives the canonicals from the group and the verb-first summary", async () => { const doc = await deferencedOpenAPI(fixture("12.page-paths")); const refs = uniform(oapSchemaToReferences(doc!, {operationPaths: "title"}), {plugins: [uniformPluginXDocsSidebar]}).references; expect(refs.map(r => r.canonical)).toEqual([ "widgets/list", "widgets/create", "widgets/retrieve", "widgets/remove", // x-docs.path wins over the derived `widgets/delete` "widgets/parts/list", // the group's noun dropped "widgets/part-snapshot/retrieve", "archiveWidget", // "Widget archival" is not verb-first "assemblies/list", // "Lists assemblies" "health", // no group "objects/color", // no group, no `object` constant: the kebab-cased name "widgets/widget", // the constant `object` value, verbatim "widgets/widget_part", "widgets/part-snapshot", "assemblies/object", // x-docs.path ]); // The grouping is the layout's, whatever the paths. expect(byCanonical(refs, "widgets/widget").context?.group).toEqual(["Objects", "widgets"]); expect(byCanonical(refs, "assemblies/object").context?.group).toEqual(["Objects", "assemblies"]); expect(byCanonical(refs, "objects/color").context?.group).toEqual(["Objects"]); // The links follow the final paths. const widget = byCanonical(refs, "widgets/widget").definitions[0]; expect(widget.symbolDef?.canonical).toBe("widgets/widget"); expect(row(widget.properties, "parts").symbolDef?.canonical).toBe("widgets/widget_part"); expect(row(widget.properties, "parts").ofProperty?.symbolDef?.canonical).toBe("widgets/widget_part"); expect(row(widget.properties, "color").symbolDef?.canonical).toBe("objects/color"); const created = byCanonical(refs, "widgets/create").definitions.find(d => d.title === "Response")!.variants![0]; expect(created.symbolDef?.canonical).toBe("widgets/widget"); const assemblies = byCanonical(refs, "assemblies/list").definitions.find(d => d.title === "Response")!.variants![0]; expect(assemblies.symbolDef?.canonical).toBe("assemblies/object"); // The hidden envelope has no page: the list root keeps its id, loses the canonical. const list = byCanonical(refs, "widgets/list").definitions.find(d => d.title === "Response")!.variants![0]; expect(list.symbolDef).toEqual({id: "#/components/schemas/WidgetList", label: "list"}); // Regions mode: the page's own canonical and its links, from the document. const page = (region: string) => uniform(oapSchemaToReferences(doc!, {regions: [region], operationPaths: "title"}), {plugins: [uniformPluginXDocsSidebar]}).references; expect(page("GET /widgets/{widgetId}/parts")[0].canonical).toBe("widgets/parts/list"); const parts = page("/components/schemas/Widget")[0]; expect(parts.canonical).toBe("widgets/widget"); expect(row(parts.definitions[0].properties, "parts").symbolDef?.canonical).toBe("widgets/widget_part"); // The default mode leaves every canonical alone. const plain = uniform(oapSchemaToReferences(doc!), {plugins: [uniformPluginXDocsSidebar]}).references; expect(plain.map(r => r.canonical)).toEqual([ "listWidgets", "createWidget", "getWidget", "widgets/remove", "listWidgetParts", "getPartSnapshot", "archiveWidget", "listAssemblies", "health", "objects/Color", "objects/Widget", "objects/WidgetPart", "objects/PartSnapshot", "assemblies/object", ]); }); it("the derivation grammar", () => { const table: [string, string, string | undefined][] = [ ["Create widget", "widgets", "widgets/create"], ["Create a widget", "widgets", "widgets/create"], ["List widgets", "widgets", "widgets/list"], ["Lists all widgets", "widgets", "widgets/list"], ["Retrieve widget", "widgets", "widgets/retrieve"], ["List widget parts", "widgets", "widgets/parts/list"], ["Retrieve part snapshot", "widgets", "widgets/part-snapshot/retrieve"], ["Delete a widget.", "widgets", "widgets/delete"], ["Searches the widget's parts", "widgets", "widgets/parts/search"], ["List parts of a widget", "widgets", "widgets/parts/list"], ["Retrieve company", "companies", "companies/retrieve"], ["List company members", "companies", "companies/members/list"], ["Create widget part", "Widget parts", "widget-parts/create"], ["Retrieve statistics", "company statistics", "company-statistics/retrieve"], ["Widget archival", "widgets", undefined], ["Returns the widget", "widgets", undefined], ["", "widgets", undefined], ["Retrieve health", "", undefined], ]; for (const [summary, group, expected] of table) { expect(operationPagePath(summary, group), `${summary} in ${group}`).toBe(expected); } expect(componentPagePath("widgets", "widget")).toBe("widgets/widget"); expect(componentPagePath("widgets", "widget_part")).toBe("widgets/widget_part"); expect(componentPagePath("Widget parts", "part")).toBe("widget-parts/part"); expect(componentPagePath(undefined, "color")).toBe("objects/color"); expect(componentPagePath("", "color")).toBe("objects/color"); expect(explicitPagePath(" /widgets//parts/list/ ")).toBe("widgets/parts/list"); expect(explicitPagePath("/")).toBeUndefined(); expect(explicitPagePath(42)).toBeUndefined(); expect(kebabCase("WidgetPart")).toBe("widget-part"); expect(kebabCase("APIKey")).toBe("api-key"); expect(kebabCase("Widget_Part")).toBe("widget-part"); expect(kebabCase("Color")).toBe("color"); expect(verbOf("Lists")).toBe("list"); expect(verbOf("Searches")).toBe("search"); expect(verbOf("Widget")).toBeUndefined(); }); it("under an x-docs.sidebar an entry's path wins over x-docs.path; an entry without one keeps it", () => { const Widget: any = { "x-docs": {name: "The widget object", path: "widgets/object"}, type: "object", properties: {id: {type: "string"}}, }; const doc: any = { openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, paths: { "/widgets": { get: { operationId: "listWidgets", summary: "List widgets", "x-docs": {path: "widgets/list"}, responses: {"200": {description: "ok", content: {"application/json": {schema: Widget}}}}, }, }, }, components: {schemas: {Widget}}, "x-docs": { sidebar: [{ group: "Reference", pages: [ {type: "endpoint", key: "listWidgets"}, {type: "object", key: "Widget", path: "the-widget"}, ], }], }, }; const refs = uniform(oapSchemaToReferences(doc), {plugins: [uniformPluginXDocsSidebar]}).references; expect(refs[0].canonical).toBe("widgets/list"); expect(refs[1].canonical).toMatch(/the-widget$/); expect(refs[1].canonical).not.toBe("widgets/object"); expect(refs[0].definitions[0].variants![0].symbolDef?.canonical).toBe(refs[1].canonical); }); it("an x-docs.sidebar that lists a hidden page still shows it", () => { const doc: any = { openapi: "3.0.3", info: {title: "Widgets", version: "1.0.0"}, paths: { "/widgets": { get: {operationId: "listWidgets", summary: "List widgets", responses: {"200": {description: "ok"}}}, }, "/internal/health": { get: {operationId: "health", summary: "Health", "x-docs": {hidden: true}, responses: {"200": {description: "ok"}}}, }, }, components: { schemas: { Widget: {"x-docs": {name: "The widget object", hidden: true}, type: "object", properties: {id: {type: "string"}}}, }, }, "x-docs": { sidebar: [{ group: "Reference", pages: [ {type: "endpoint", key: "health"}, {type: "object", key: "Widget"}, ], }], }, }; const refs = uniform(oapSchemaToReferences(doc), {plugins: [uniformPluginXDocsSidebar]}).references; expect(refs.map(r => r.title)).toEqual(["Health", "The widget object"]); expect(refs.map(r => r.context?.group)).toEqual([["Reference"], ["Reference"]]); }); }); const URL_PREFIX = "docs/api"; /** The generated navigation in pluginNavigation's emitted shape — one group * node per `context.group` path, a `{virtual, page}` leaf per page (the page * path itself in store mode). pluginNavigation itself runs natively only; * the fused goldens pin the real output. */ function navigationOf(refs: Reference[], store = false): NavigationGroupEntry[] { const root: NavigationGroupEntry[] = []; for (const ref of refs) { const group = Array.isArray(ref.context?.group) ? (ref.context!.group as string[]) : []; if (!group.length) continue; let level = root; let node: NavigationGroupEntry | undefined; for (const name of group) { node = level.find(e => e.group === name); if (!node) { node = {group: name, pages: []}; level.push(node); } level = node.pages as NavigationGroupEntry[]; } const page = path.join(URL_PREFIX, ref.canonical); node!.pages!.push(store ? page : {virtual: path.join(".xyd/.cache/.content", page), page}); } return root; } const flagsIn = (sidebar: unknown) => (JSON.stringify(sidebar).match(/"collapsed"/g) ?? []).length; describe("the Objects group's collapsed flag (JS impl)", () => { async function sidebarFor(options?: any, mutate?: (doc: any) => void, store = false) { const doc = await deferencedOpenAPI(fixture("5.xdocs.objects")); mutate?.(doc); const refs = uniform(oapSchemaToReferences(doc!, options), {plugins: [uniformPluginXDocsSidebar]}).references; const nav = navigationOf(refs, store); const before = JSON.stringify(nav); const sidebar = collapseObjectsGroup(nav, doc as any, refs, URL_PREFIX, options); expect(JSON.stringify(nav)).toBe(before); // the input is not mutated return sidebar; } it("the top-level Objects group carries `collapsed: true`, and nothing else does", async () => { const sidebar = await sidebarFor(); expect(sidebar.map(e => e.group)).toEqual(["widgets", "Objects"]); const objects = sidebar[1]; expect(objects.collapsed).toBe(true); expect(Object.keys(objects)).toEqual(["group", "collapsed", "pages"]); // Not the operation group above it, not the area sub-groups inside it. expect("collapsed" in sidebar[0]).toBe(false); const subGroups = (objects.pages as NavigationGroupEntry[]).filter(p => "group" in p); expect(subGroups.map(g => g.group)).toEqual(["widgets", "parts"]); expect(subGroups.every(g => !("collapsed" in g))).toBe(true); expect(flagsIn(sidebar)).toBe(1); }); it("an operation in the objects group keeps it open — an operation group never carries the flag", async () => { const sidebar = await sidebarFor(undefined, doc => { doc.tags = [...(doc.tags ?? []), {name: "Objects"}]; doc.paths["/objects"] = { get: {operationId: "listObjects", summary: "List objects", tags: ["Objects"], responses: {"200": {description: "ok"}}}, }; }); const objects = sidebar.find(e => e.group === "Objects")!; expect((objects.pages as any[]).some(p => p.page === "docs/api/listObjects")).toBe(true); expect(flagsIn(sidebar)).toBe(0); }); it("objectsCollapsed: false leaves the group open; the renamed group carries the flag", async () => { const open = await sidebarFor({objectsCollapsed: false}); expect(flagsIn(open)).toBe(0); const byDefault = await sidebarFor(); const {collapsed: _flag, ...objectsOpen} = byDefault[1]; expect(open).toEqual([byDefault[0], objectsOpen]); expect(await sidebarFor({objectsCollapsed: true})).toEqual(byDefault); const renamed = await sidebarFor({objectsGroup: "Types"}); expect(renamed.find(e => e.group === "Types")?.collapsed).toBe(true); expect(flagsIn(renamed)).toBe(1); // The option's default. expect(objectsCollapsedOf(undefined)).toBe(true); expect(objectsCollapsedOf({})).toBe(true); expect(objectsCollapsedOf({objectsCollapsed: true})).toBe(true); expect(objectsCollapsedOf({objectsCollapsed: false})).toBe(false); }); it("per-area and sidebar mode are untouched", async () => { const perArea = await sidebarFor({objectsLayout: "per-area"}); expect(perArea.some(e => e.group === "Objects")).toBe(true); expect(flagsIn(perArea)).toBe(0); // Even a sidebar group named like the objects group that lists object // pages only: the author's navigation is never folded by this pass. const withSidebar = await sidebarFor(undefined, doc => { doc["x-docs"] = { sidebar: [ {group: "widgets", pages: [{type: "endpoint", key: "listWidgets"}]}, {group: "Objects", pages: [{type: "object", key: "Widget"}, {type: "object", key: "Part"}]}, ], }; }); expect(withSidebar.some(e => e.group === "Objects")).toBe(true); expect(flagsIn(withSidebar)).toBe(0); }); it("store mode lists the pages as plain paths; they are recognised too", async () => { const sidebar = await sidebarFor(undefined, undefined, true); const objects = sidebar.find(e => e.group === "Objects")!; expect(objects.pages![0]).toBe("docs/api/objects/PartBase"); expect(objects.collapsed).toBe(true); expect(flagsIn(sidebar)).toBe(1); }); }); describe("tag groups and display names (JS impl)", () => { const OBJECTS = "Objects"; const operation = (operationId: string, summary: string, tag: string) => ({ operationId, summary, tags: [tag], responses: {"200": {description: "ok"}}, }); const object = (name: string, group?: string) => ({ "x-docs": group ? {name: `The ${name} object`, group} : {name: `The ${name} object`}, type: "object", properties: {id: {type: "string"}}, }); /** The twin of the Rust unit tests' store: one operation per tag — `pets`, * `store`, `users`, `audit`, the declared order — a `Money` object page * without an area, a `Pet` one in the `pets` area and a `Report` one in * `reports` (a declared tag with no operations). `displayNames` gives tags * an `x-displayName`; `root` merges document keys. */ function petstoreDoc(displayNames: Record = {}, root: Record = {}): any { return { openapi: "3.0.3", info: {title: "Petstore", version: "1.0.0"}, tags: ["pets", "store", "users", "audit", "reports"].map(name => name in displayNames ? {name, [DISPLAY_NAME_KEY]: displayNames[name]} : {name}), paths: { "/pets": {get: operation("listPets", "List pets", "pets")}, "/store/inventory": {get: operation("getInventory", "Retrieve inventory", "store")}, "/users": {get: operation("listUsers", "List users", "users")}, "/audit": {get: operation("listAuditEvents", "List audit events", "audit")}, }, components: { schemas: { Money: object("money"), Pet: object("pet", "pets"), Report: object("report", "reports"), }, }, ...root, }; } const withTagGroups = (groups: unknown) => petstoreDoc({}, {[TAG_GROUPS_KEY]: groups}); function sidebarFor(doc: any, options?: any, store = false): NavigationGroupEntry[] { const refs = uniform(oapSchemaToReferences(doc, options), {plugins: [uniformPluginXDocsSidebar]}).references; return collapseObjectsGroup(navigationOf(refs, store), doc, refs, URL_PREFIX, options); } /** Both finishing passes, in the fused endpoint's order. */ function groupedFor(doc: any, options?: any, store = false): NavigationGroupEntry[] { const base = sidebarFor(doc, options, store); const before = JSON.stringify(base); const out = groupByTagGroups(base, doc); expect(JSON.stringify(base)).toBe(before); // the input is not mutated return out; } const names = (level: unknown[]) => level .filter((e): e is NavigationGroupEntry => !!e && typeof e === "object" && "group" in e) .map(e => e.group); const entry = (level: NavigationGroupEntry[], group: string) => { const found = level.find(e => e.group === group); if (!found) { throw new Error(`no group ${group} in ${JSON.stringify(names(level))}`); } return found; }; const pagesOf = (e: unknown) => (e as NavigationGroupEntry).pages as NavigationGroupEntry[]; const base = () => sidebarFor(petstoreDoc()); it("the baseline: four area groups in the tag order, then the collapsed objects group", () => { const sidebar = base(); expect(names(sidebar)).toEqual(["pets", "store", "users", "audit", OBJECTS]); const objects = entry(sidebar, OBJECTS); expect((pagesOf(objects)[0] as any).page).toBe("docs/api/objects/Money"); expect(names(pagesOf(objects))).toEqual(["pets", "reports"]); }); it("two sections take the place of their first member; members follow the tag group's order and move whole", () => { const doc = () => withTagGroups([ {name: "Core", tags: ["store", "pets"]}, {name: "Admin", tags: ["audit", "users"]}, ]); const before = sidebarFor(doc()); const sidebar = groupedFor(doc()); expect(names(sidebar)).toEqual(["Core", "Admin", OBJECTS]); const core = entry(sidebar, "Core"); expect(Object.keys(core)).toEqual(["group", "pages"]); expect(names(pagesOf(core))).toEqual(["store", "pets"]); expect(pagesOf(core)[0]).toEqual(entry(before, "store")); expect(pagesOf(core)[1]).toEqual(entry(before, "pets")); expect(names(pagesOf(entry(sidebar, "Admin")))).toEqual(["audit", "users"]); expect(entry(sidebar, OBJECTS)).toEqual(entry(before, OBJECTS)); expect(flagsIn(sidebar)).toBe(1); }); it("an entry no tag group lists keeps its place", () => { const sidebar = groupedFor(withTagGroups([{name: "Core", tags: ["store", "users"]}])); expect(names(sidebar)).toEqual(["pets", "Core", "audit", OBJECTS]); expect(names(pagesOf(entry(sidebar, "Core")))).toEqual(["store", "users"]); }); it("a listed name without a top-level entry adds nothing; a section without members is not emitted", () => { const sidebar = groupedFor(withTagGroups([ {name: "Core", tags: ["pets", "reports", "billing"]}, {name: "Admin", tags: ["billing"]}, ])); expect(names(sidebar)).toEqual(["Core", "store", "users", "audit", OBJECTS]); expect(names(pagesOf(entry(sidebar, "Core")))).toEqual(["pets"]); expect(names(pagesOf(entry(sidebar, OBJECTS)))).toEqual(["pets", "reports"]); }); it("the first tag group listing a name wins; a repeated section name is skipped", () => { const sidebar = groupedFor(withTagGroups([ {name: "Core", tags: ["pets", "store"]}, {name: "Admin", tags: ["store", "users"]}, {name: "Core", tags: ["audit"]}, ])); expect(names(sidebar)).toEqual(["Core", "Admin", "audit", OBJECTS]); expect(names(pagesOf(entry(sidebar, "Core")))).toEqual(["pets", "store"]); expect(names(pagesOf(entry(sidebar, "Admin")))).toEqual(["users"]); }); it("a section never shares a name (or a display name) with a top-level entry that keeps its place", () => { expect(groupedFor(withTagGroups([{name: "audit", tags: ["pets", "store"]}]))).toEqual(base()); expect(groupedFor(withTagGroups([ {name: "pets", tags: ["store"]}, {name: "store", tags: ["users"]}, ]))).toEqual(base()); const intoItself = groupedFor(withTagGroups([{name: "pets", tags: ["pets", "store"]}])); expect(names(intoItself)).toEqual(["pets", "users", "audit", OBJECTS]); expect(names(pagesOf(intoItself[0]))).toEqual(["pets", "store"]); const elsewhere = groupedFor(withTagGroups([ {name: "Core", tags: ["pets"]}, {name: "pets", tags: ["store"]}, ])); expect(names(elsewhere)).toEqual(["Core", "pets", "users", "audit", OBJECTS]); expect(names(pagesOf(elsewhere[0]))).toEqual(["pets"]); expect(names(pagesOf(elsewhere[1]))).toEqual(["store"]); // Named like the display name of an entry that keeps its place: the // tag group is skipped, so the navigation is the relabelled baseline. const labelledLike = groupedFor(petstoreDoc({pets: "Core"}, {[TAG_GROUPS_KEY]: [{name: "Core", tags: ["store"]}]})); expect(names(labelledLike)).toEqual(["Core", "store", "users", "audit", OBJECTS]); expect(pagesOf(labelledLike[0])).toEqual(pagesOf(base()[0])); expect(labelledLike[1]).toEqual(base()[1]); expect(labelledLike).toEqual(groupedFor(petstoreDoc({pets: "Core"}))); }); it("display names label the groups at any depth; sections, page entries and key order are untouched", () => { const displayNames = {pets: "Pets", store: "Store", reports: "Reports"}; const doc = () => petstoreDoc(displayNames, {[TAG_GROUPS_KEY]: [{name: "Core", tags: ["pets", "store"]}]}); const before = sidebarFor(doc()); const sidebar = groupedFor(doc()); expect(names(sidebar)).toEqual(["Core", "users", "audit", OBJECTS]); const core = entry(sidebar, "Core"); expect(names(pagesOf(core))).toEqual(["Pets", "Store"]); expect(pagesOf(pagesOf(core)[0])).toEqual(pagesOf(entry(before, "pets"))); const objects = entry(sidebar, OBJECTS); expect(Object.keys(objects)).toEqual(["group", "collapsed", "pages"]); expect(names(pagesOf(objects))).toEqual(["Pets", "Reports"]); expect(pagesOf(objects)[0]).toEqual(pagesOf(entry(before, OBJECTS))[0]); // Display names alone: the same navigation, relabelled. expect(names(groupedFor(petstoreDoc(displayNames)))).toEqual(["Pets", "Store", "users", "audit", OBJECTS]); // A section named like a display-named tag keeps its own name. const namedLikeATag = groupedFor(petstoreDoc(displayNames, {[TAG_GROUPS_KEY]: [{name: "pets", tags: ["pets"]}]})); expect(namedLikeATag[0].group).toBe("pets"); expect(names(pagesOf(namedLikeATag[0]))).toEqual(["Pets"]); // The first tag of a name decides, with or without a display name. const repeated = petstoreDoc({pets: "Pets"}); repeated.tags.push({name: "pets", [DISPLAY_NAME_KEY]: "Animals"}, {name: "store", [DISPLAY_NAME_KEY]: "Shop"}); expect(names(groupedFor(repeated))).toEqual(["Pets", "store", "users", "audit", OBJECTS]); }); it("the per-area layout: an area moves into its section whole, its objects sub-group with it", () => { const options = {objectsLayout: "per-area"}; const doc = () => withTagGroups([{name: "Core", tags: ["pets", "reports"]}]); const before = sidebarFor(doc(), options); expect(names(pagesOf(entry(before, "pets")))).toEqual([OBJECTS]); const sidebar = groupedFor(doc(), options); expect(names(sidebar)).toEqual( names(before).filter(n => n !== "reports").map(n => n === "pets" ? "Core" : n)); expect(pagesOf(entry(sidebar, "Core"))).toEqual([entry(before, "pets"), entry(before, "reports")]); expect(flagsIn(sidebar)).toBe(0); }); it("store mode: the page paths inside a moved, relabelled group are untouched", () => { const sidebar = groupedFor(petstoreDoc({pets: "Pets"}, {[TAG_GROUPS_KEY]: [{name: "Core", tags: ["pets"]}]}), undefined, true); const core = entry(sidebar, "Core"); expect(names(pagesOf(core))).toEqual(["Pets"]); expect(pagesOf(pagesOf(core)[0])).toEqual(["docs/api/listPets"]); }); it("malformed tag groups are skipped; a well-formed one beside them still applies", () => { const sidebar = groupedFor(withTagGroups([ 42, {name: "Admin"}, {tags: ["users"]}, {name: "", tags: ["users"]}, {name: 7, tags: ["users"]}, {name: "Ops", tags: "audit"}, {name: "Core", tags: ["store", 7, "", null, "pets"]}, ])); expect(names(sidebar)).toEqual(["Core", "users", "audit", OBJECTS]); expect(names(pagesOf(entry(sidebar, "Core")))).toEqual(["store", "pets"]); }); it("without a well-formed tag group or a non-empty string display name the pass changes nothing", () => { expect(groupedFor(petstoreDoc())).toEqual(base()); const malformed = petstoreDoc({pets: ""}, {[TAG_GROUPS_KEY]: [42, {name: "Core"}, {tags: ["pets"]}]}); malformed.tags[1][DISPLAY_NAME_KEY] = 7; expect(groupedFor(malformed)).toEqual(base()); expect(groupedFor(withTagGroups({name: "Core", tags: ["pets"]}))).toEqual(base()); // A sidebar without either extension comes back as it is. const sidebar = base(); expect(groupByTagGroups(sidebar, petstoreDoc())).toBe(sidebar); }); it("sidebar mode is the author's navigation: untouched", () => { const doc = () => petstoreDoc({pets: "Pets"}, { [TAG_GROUPS_KEY]: [{name: "Core", tags: ["pets", "store"]}], "x-docs": { sidebar: [ {group: "pets", pages: [{type: "endpoint", key: "listPets"}]}, {group: "store", pages: [{type: "endpoint", key: "getInventory"}]}, ], }, }); const before = sidebarFor(doc()); expect(names(before)).toEqual(["pets", "store"]); expect(groupedFor(doc())).toEqual(before); }); it("the package entry exports the pass and its keys", () => { expect(packageEntry.groupByTagGroups).toBe(groupByTagGroups); expect(packageEntry.TAG_GROUPS_KEY).toBe("x-tagGroups"); expect(packageEntry.DISPLAY_NAME_KEY).toBe("x-displayName"); }); });