docs: generate pricing module reference (#5349)

* docs: generate pricing module reference

* added notes about new configurations
This commit is contained in:
Shahed Nasser
2023-10-11 14:08:19 +03:00
committed by GitHub
parent 9c1c19f409
commit f0af8ecc89
110 changed files with 7170 additions and 146 deletions

View File

@@ -10,40 +10,46 @@ module.exports = ({
tsconfigPath = "",
moduleName = "",
documentsToFormat = [],
additionalFormatting = {},
extraOptions = {},
}) => {
const formatting = {}
documentsToFormat.forEach((document) => {
formatting[document] = {
reflectionTitle: {
kind: false,
typeParameters: false,
suffix: "Reference",
},
expandMembers: true,
showCommentsAsHeader: true,
parameterStyle: "list",
useTsLinkResolution: false,
showReturnSignature: false,
sections: {
reflection_typeParameters: false,
member_declaration_typeParameters: false,
reflection_implements: false,
reflection_implementedBy: false,
reflection_callable: false,
reflection_indexable: false,
member_signature_typeParameters: false,
member_signature_sources: false,
member_signature_title: false,
},
reflectionGroups: {
Constructors: false,
Properties: false,
},
...additionalFormatting,
documentsToFormat.forEach(
({ pattern, additionalFormatting, useDefaults = false }) => {
formatting[pattern] = {
...(!useDefaults
? {
reflectionTitle: {
kind: false,
typeParameters: false,
suffix: "Reference",
},
expandMembers: true,
showCommentsAsHeader: true,
parameterStyle: "list",
useTsLinkResolution: false,
showReturnSignature: false,
sections: {
reflection_typeParameters: false,
member_declaration_typeParameters: false,
reflection_implements: false,
reflection_implementedBy: false,
reflection_callable: false,
reflection_indexable: false,
member_signature_typeParameters: false,
member_signature_sources: false,
member_signature_title: false,
title_reflectionPath: false,
},
reflectionGroups: {
Constructors: false,
Properties: false,
},
}
: {}),
...additionalFormatting,
}
}
})
)
return {
...globalTypedocOptions,
entryPoints: [path.join(pathPrefix, entryPointPath)],
@@ -66,6 +72,7 @@ module.exports = ({
],
hideMembersSymbol: true,
formatting,
allReflectionsHaveOwnDocument: true,
...extraOptions,
}
}

View File

@@ -5,14 +5,62 @@ module.exports = modulesConfig({
entryPointPath: "packages/types/src/pricing/service.ts",
outPath: "www/apps/docs/content/references/pricing",
moduleName: "Pricing Module Reference",
documentsToFormat: ["IPricingModuleService"],
additionalFormatting: {
reflectionDescription:
"This document provides a reference to the `IPricingModuleService` interfaces methods. This is the interface developers use to use the functionalities provided by the Pricing Module.",
},
extraOptions: {
frontmatterData: {
displayed_sidebar: "modules",
documentsToFormat: [
{
pattern: "IPricingModuleService.md",
additionalFormatting: {
reflectionDescription:
"This section of the documentation provides a reference to the `IPricingModuleService` interfaces methods. This is the interface developers use to use the functionalities provided by the Pricing Module.",
frontmatterData: {
displayed_sidebar: "pricingReference",
badge: {
variant: "orange",
text: "Beta",
},
slug: "/references/pricing",
// hide_table_of_contents: true,
},
},
},
{
pattern: "IPricingModuleService/methods",
additionalFormatting: {
reflectionDescription:
"This documentation provides a reference to the {{alias}} {{kind}}. This belongs to the Pricing Module.",
frontmatterData: {
displayed_sidebar: "pricingReference",
badge: {
variant: "orange",
text: "Beta",
},
slug: "/references/pricing/{{alias}}",
sidebar_label: "{{alias}}",
},
reflectionTitle: {
kind: false,
typeParameters: false,
suffix: "- Pricing Module Reference",
},
},
},
{
pattern: "*",
useDefaults: true,
additionalFormatting: {
frontmatterData: {
displayed_sidebar: "pricingReference",
},
},
},
],
extraOptions: {
// frontmatterData: {
// displayed_sidebar: "modules",
// badge: {
// variant: "orange",
// text: "Beta",
// },
// // hide_table_of_contents: true,
// },
},
})

View File

@@ -2,6 +2,8 @@
A Typedoc plugin that allows inserting frontmatter key-value pairs at the top of the exported Markdown files.
> For more flexibility in what pages to apply the frontmatter data to, for example, to specify different frontmatter for different pages, ues the [`typedoc-plugin-markdown-medusa` plugin's `frontmatterData` option](../typedoc-plugin-markdown-medusa/README.md#configurations)
## Configurations
The following options are optional and can be used to customize the configurations of the plugin.

View File

@@ -30,5 +30,8 @@
"packages",
"monorepo",
"typedoc"
]
],
"dependencies": {
"yaml": "^2.3.2"
}
}

View File

@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Application, PageEvent, ParameterType } from "typedoc"
import { stringify } from "yaml"
export function load(app: Application) {
app.options.addDeclaration({
@@ -35,20 +36,15 @@ export function load(app: Application) {
if (typeof frontmatterData === "string") {
frontmatterData = JSON.parse(frontmatterData)
}
const frontmatterDataEntries = Object.entries(frontmatterData)
if (!frontmatterDataEntries.length || !pattern.test(page.filename)) {
if (!pattern.test(page.filename) || !Object.keys(frontmatterData).length) {
return
}
let frontmatterStr = `---\n`
const frontmatterStr = stringify(frontmatterData)
for (const [key, value] of frontmatterDataEntries) {
frontmatterStr += `${key}: ${value}\n`
if (frontmatterStr.length) {
page.contents = `---\n` + frontmatterStr + `---\n\n` + page.contents
}
frontmatterStr += `---\n\n`
page.contents = frontmatterStr + page.contents
})
}

View File

@@ -16,8 +16,11 @@ Aside from the options detailed in [typedoc-plugin-markdown](https://github.com/
- `reflectionDescription`: (optional) a string used to add description in a documentation page after the page's title.
- `expandMembers`: (optional) a boolean indicating whether members in a page should be expanded. When enabled, the member titles (for example, `Methods`) are removed and the heading level of nested titles whithin the member is elevated by `1`.
- `showCommentAsHeader`: (optional) a boolean indicating whether comments, for example, a method's name, are represented as headers.
- `showCommentsAsDetails`: (optional) a boolean indicating whether comments, for example, a method's name, are represented as details component.
- `parameterStyle`: (optional) a string indicating how parameters are displayed. Its value can be `table` (default) or `list`.
- `showReturnSignature`: (optional) a boolean indicating whether to show the signature for returned values.
- `frontmatterData`: (optional) an object that will be injected as frontmatter to the pages matching specified pattern.
-
## Build Plugin

View File

@@ -32,6 +32,7 @@
"typedoc"
],
"dependencies": {
"handlebars": "^4.7.8"
"handlebars": "^4.7.8",
"yaml": "^2.3.2"
}
}

View File

@@ -35,6 +35,8 @@ import typeParameterHelper from "./resources/helpers/type-parameter"
import parameterListHelper from "./resources/helpers/parameter-list"
import parameterHelper from "./resources/helpers/parameter"
import debugHelper from "./resources/helpers/debug"
import frontmatterHelper from "./resources/helpers/frontmatter"
import reflectionDescriptionHelper from "./resources/helpers/reflection-description"
import { MarkdownTheme } from "./theme"
const TEMPLATE_PATH = path.join(__dirname, "resources", "templates")
@@ -98,4 +100,6 @@ export function registerHelpers(theme: MarkdownTheme) {
parameterListHelper()
parameterHelper(theme)
debugHelper()
frontmatterHelper(theme)
reflectionDescriptionHelper(theme)
}

View File

@@ -13,7 +13,8 @@ export default function (theme: MarkdownTheme) {
commentLevel = 4,
parent = null
) {
const { showCommentsAsHeader } = theme.getFormattingOptionsForLocation()
const { showCommentsAsHeader, showCommentsAsDetails } =
theme.getFormattingOptionsForLocation()
const md: string[] = []
if (showSummary && comment.summary) {
@@ -26,16 +27,19 @@ export default function (theme: MarkdownTheme) {
if (showTags && comment.blockTags?.length) {
const tags = filteredTags.map((tag) => {
return `${
showCommentsAsHeader
? `${Handlebars.helpers.titleLevel.call(
parent || comment,
commentLevel
)} `
: "**`"
}${camelToTitleCase(tag.tag.substring(1))}${
showCommentsAsHeader ? "" : "`**"
}\n\n${Handlebars.helpers.comment(tag.content)}`
const tagTitle = camelToTitleCase(tag.tag.substring(1)),
tagContent = Handlebars.helpers.comment(tag.content)
if (showCommentsAsHeader) {
return `${Handlebars.helpers.titleLevel.call(
parent || comment,
commentLevel
)} ${tagTitle}\n\n${tagContent}`
} else if (showCommentsAsDetails) {
return `<details>\n<summary>\n${tagTitle}\n</summary>\n\n${tagContent}\n\n</details>`
} else {
return `**${tagTitle}**\n\n${tagContent}`
}
})
md.push(tags.join("\n\n"))
}

View File

@@ -0,0 +1,47 @@
import * as Handlebars from "handlebars"
import { MarkdownTheme } from "../../theme"
import { stringify } from "yaml"
import { replaceTemplateVariables } from "../../utils/reflection-template-strings"
import { Reflection } from "typedoc"
export default function (theme: MarkdownTheme) {
Handlebars.registerHelper("frontmatter", function (this: Reflection) {
const { frontmatterData } = theme.getFormattingOptionsForLocation()
if (!frontmatterData) {
return ""
}
// format frontmatter data in case it has any template variables
return `---\n${stringify(
resolveFrontmatterVariables(frontmatterData, this)
).trim()}\n---\n\n`
})
}
function resolveFrontmatterVariables(
frontmatterData: Record<string, unknown>,
reflection: Reflection
): Record<string, unknown> {
const tempFrontmatterData = Object.assign({}, frontmatterData)
Object.keys(tempFrontmatterData).forEach((key) => {
const value = tempFrontmatterData[key]
if (!value) {
return
}
switch (typeof value) {
case "object":
tempFrontmatterData[key] = resolveFrontmatterVariables(
value as Record<string, unknown>,
reflection
)
break
case "string":
tempFrontmatterData[key] = replaceTemplateVariables(reflection, value)
}
})
return tempFrontmatterData
}

View File

@@ -0,0 +1,16 @@
import * as Handlebars from "handlebars"
import { MarkdownTheme } from "../../theme"
import { Reflection } from "typedoc"
import { replaceTemplateVariables } from "../../utils/reflection-template-strings"
export default function (theme: MarkdownTheme) {
Handlebars.registerHelper(
"reflectionDescription",
function (this: Reflection) {
const { reflectionDescription } = theme.getFormattingOptionsForLocation()
// parse variables in description
return replaceTemplateVariables(this, reflectionDescription)
}
)
}

View File

@@ -9,6 +9,12 @@ export default function (theme: MarkdownTheme) {
const { expandMembers, sections } =
theme.getFormattingOptionsForLocation()
if (!expandMembers) {
return Array(originalLevel).fill("#").join("")
}
const { allReflectionsHaveOwnDocument } = theme
let isSignatureChild = false
if (
sections &&
@@ -22,8 +28,15 @@ export default function (theme: MarkdownTheme) {
(this.parent.signatures as SignatureReflection[]).length > 1
}
const level =
expandMembers && !isSignatureChild ? originalLevel - 1 : originalLevel
const numberToSubtract = allReflectionsHaveOwnDocument
? isSignatureChild
? 1
: 2
: isSignatureChild
? 0
: 1
const level = originalLevel - numberToSubtract
return Array(level).fill("#").join("")
}

View File

@@ -4,7 +4,11 @@
{{/ifShowPageTitle}}
{{{getFormattingOption "reflectionDescription"}}}
{{#with model}}
{{{reflectionDescription}}}
{{/with}}
{{#if (sectionEnabled "title_reflectionPath")}}

View File

@@ -1,3 +1,9 @@
{{#with model}}
{{{frontmatter}}}
{{/with}}
{{> header}}
{{#with model.readme}}

View File

@@ -1,3 +1,9 @@
{{#with model}}
{{{frontmatter}}}
{{/with}}
{{> header}}
{{> title}}

View File

@@ -1,3 +1,9 @@
{{#with model}}
{{{frontmatter}}}
{{/with}}
{{> header}}
{{> title}}

View File

@@ -13,7 +13,6 @@ import {
Theme,
UrlMapping,
} from "typedoc"
import { getKindPlural } from "./groups"
import {
indexTemplate,
reflectionMemberTemplate,
@@ -26,7 +25,6 @@ import {
FormattingOptionType,
FormattingOptionsType,
Mapping,
NavigationItem,
ObjectLiteralDeclarationStyle,
} from "./types"
@@ -139,9 +137,9 @@ export class MarkdownTheme extends Theme {
reflection: DeclarationReflection,
urls: UrlMapping[]
): UrlMapping[] {
const mapping = this.mappings.find((mapping) =>
reflection.kindOf(mapping.kind)
)
const mapping = this.getMappings(
reflection.parent?.isProject() ? "" : reflection.parent?.getAlias()
).find((mapping) => reflection.kindOf(mapping.kind))
if (mapping) {
if (!reflection.url || !MarkdownTheme.URL_PREFIX.test(reflection.url)) {
const url = this.toUrl(mapping, reflection)
@@ -266,103 +264,36 @@ export class MarkdownTheme extends Theme {
}
}
getNavigation(project: ProjectReflection) {
const urls = this.getUrls(project)
const getUrlMapping = (name: string) => {
if (!name) {
return ""
}
return urls.find((url) => url.model.name === name)
}
const createNavigationItem = (
title: string,
url: string | undefined,
isLabel: boolean,
children: NavigationItem[] = []
) => {
const navigationItem = new NavigationItem(title, url)
navigationItem.isLabel = isLabel
navigationItem.children = children
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { reflection, parent, ...filteredNavigationItem } = navigationItem
return filteredNavigationItem as NavigationItem
}
const navigation = createNavigationItem(project.name, undefined, false)
const hasReadme = !this.readme.endsWith("none")
if (hasReadme) {
navigation.children?.push(
createNavigationItem("Readme", this.entryDocument, false)
)
}
if (this.entryPoints.length === 1) {
navigation.children?.push(
createNavigationItem(
"Exports",
hasReadme ? this.globalsFile : this.entryDocument,
false
)
)
}
this.mappings.forEach((mapping) => {
const kind = mapping.kind[0]
const items = project.getReflectionsByKind(kind)
if (items.length > 0) {
const children = items
.map((item) => {
const urlMapping = getUrlMapping(item.name) || ""
return createNavigationItem(
item.getFullName(),
typeof urlMapping === "string" ? urlMapping : urlMapping.url,
true
)
})
.sort((a, b) => {
return a.title > b.title ? 1 : -1
})
const group = createNavigationItem(
getKindPlural(kind),
undefined,
true,
children
)
navigation.children?.push(group)
}
})
return navigation
}
get mappings(): Mapping[] {
getMappings(directoryPrefix?: string): Mapping[] {
return [
{
kind: [ReflectionKind.Module],
isLeaf: false,
directory: "modules",
directory: path.join(directoryPrefix || "", "modules"),
template: this.getReflectionTemplate(),
},
{
kind: [ReflectionKind.Namespace],
isLeaf: false,
directory: "modules",
directory: path.join(directoryPrefix || "", "modules"),
template: this.getReflectionTemplate(),
},
{
kind: [ReflectionKind.Enum],
isLeaf: false,
directory: "enums",
directory: path.join(directoryPrefix || "", "enums"),
template: this.getReflectionTemplate(),
},
{
kind: [ReflectionKind.Class],
isLeaf: false,
directory: "classes",
directory: path.join(directoryPrefix || "", "classes"),
template: this.getReflectionTemplate(),
},
{
kind: [ReflectionKind.Interface],
isLeaf: false,
directory: "interfaces",
directory: path.join(directoryPrefix || "", "interfaces"),
template: this.getReflectionTemplate(),
},
...(this.allReflectionsHaveOwnDocument
@@ -370,19 +301,25 @@ export class MarkdownTheme extends Theme {
{
kind: [ReflectionKind.TypeAlias],
isLeaf: true,
directory: "types",
directory: path.join(directoryPrefix || "", "types"),
template: this.getReflectionMemberTemplate(),
},
{
kind: [ReflectionKind.Variable],
isLeaf: true,
directory: "variables",
directory: path.join(directoryPrefix || "", "variables"),
template: this.getReflectionMemberTemplate(),
},
{
kind: [ReflectionKind.Function],
isLeaf: true,
directory: "functions",
directory: path.join(directoryPrefix || "", "functions"),
template: this.getReflectionMemberTemplate(),
},
{
kind: [ReflectionKind.Method],
isLeaf: true,
directory: path.join(directoryPrefix || "", "methods"),
template: this.getReflectionMemberTemplate(),
},
]

View File

@@ -68,8 +68,10 @@ export type FormattingOptionType = {
reflectionDescription?: string
expandMembers?: boolean
showCommentsAsHeader?: boolean
showCommentsAsDetails?: boolean
parameterStyle?: ParameterStyle
showReturnSignature?: boolean
frontmatterData?: Record<string, unknown>
}
export type FormattingOptionsType = {

View File

@@ -0,0 +1,25 @@
import { Reflection, ReflectionKind } from "typedoc"
export function replaceTemplateVariables(
reflection: Reflection,
text?: string
): string {
if (!text) {
return ""
}
return text
.replaceAll("{{alias}}", reflection.getAlias())
.replaceAll("{{kind}}", getKindAsText(reflection.kind))
}
export function getKindAsText(kind: ReflectionKind) {
switch (kind) {
case ReflectionKind.Method:
return "method"
case ReflectionKind.Enum:
return "enum"
default:
return ""
}
}