Files
video.js-mirror/packages/spf/scripts/reference/render.ts

1118 lines
45 KiB
TypeScript

/**
* Renders the model as Markdown pages, one per public entry, plus a README index. Pages hold only what the model read
* from the sources. A state or context key one behavior leaves undocumented borrows the doc of the behavior that writes
* it (else the first that reads it), with the lender named; an undocumented type export shows what it declares; a
* symbol with no doc anywhere is marked "No description." and nothing more.
*/
import { dirname, relative } from 'node:path';
import ts from 'typescript';
import type {
BehaviorInfo,
ConfigRow,
DefaultValue,
DocBlock,
EngineInfo,
FeatureInfo,
Model,
Owner,
SlotRow,
TypeField,
} from './model';
import {
declarationSignature,
declaringFile,
docOf,
exportKind,
exportedLiteral,
firstSentence,
moduleDoc,
moduleExports,
resolveAlias,
declaredTypeOf,
} from './model';
import type { EntryPoint, ReferenceProgram } from './program';
export const GENERATED_NOTICE =
'<!-- Generated by `pnpm -F @videojs/spf docs:reference`. Do not edit by hand; edit the JSDoc in the source. -->';
const NO_DESCRIPTION = 'No description.';
const LONG_CELL = 200;
const CORE_MODULE_PREFIX = './core/composition/';
/** Pages keyed by their path under the reference root. */
export type Pages = Map<string, string>;
// ── Markdown helpers ─────────────────────────────────────────────────────────
/** GitHub's heading anchor for a plain-text heading. */
function anchor(heading: string): string {
return heading
.toLowerCase()
.replace(/[^\w\- ]/g, '')
.replace(/ /g, '-');
}
function link(fromPage: string, toPage: string, label: string, fragment = ''): string {
const path = relative(dirname(fromPage), toPage) || '.';
return `[${label}](${path}${fragment ? `#${fragment}` : ''})`;
}
/** A link from a page to a source file, as a path relative to the page. */
function sourceLink(reference: ReferenceProgram, fromPage: string, file: string): string {
const docsDir = `${reference.packageDir}/docs/reference`;
const relativeToRoot = relative(reference.packageDir, file);
const path = relative(dirname(`${docsDir}/${fromPage}`), file);
return `[${relativeToRoot}](${path})`;
}
function cell(text: string): string {
return text
.replace(/\s*\n\s*/g, ' ')
.replace(/\|/g, '\\|')
.trim();
}
function code(text: string): string {
return `\`${text.replace(/`/g, '\\`')}\``;
}
function table(headers: string[], rows: string[][]): string {
const lines = [`| ${headers.join(' | ')} |`, `| ${headers.map(() => '---').join(' | ')} |`];
for (const row of rows) lines.push(`| ${row.map(cell).join(' | ')} |`);
return lines.join('\n');
}
function fence(language: string, body: string): string {
return `\`\`\`${language}\n${body.trimEnd()}\n\`\`\``;
}
/**
* Dedent an `@example` body and keep it a fenced block; one that is already fenced is used as written. The tag's first
* line comes without its indent, so the indent is measured on the lines after it.
*/
export function exampleBlock(text: string): string {
const [first = '', ...rest] = text.split('\n');
const indented = rest.filter((line) => line.trim());
const indent = indented.length ? Math.min(...indented.map((line) => line.length - line.trimStart().length)) : 0;
const body = [first.trim(), ...rest.map((line) => line.slice(indent))].join('\n').trim();
// The formatter leaves `;` after a closing fence inside JSDoc; it would keep the block open in Markdown.
if (body.startsWith('```')) return body.replace(/```;\s*$/, '```');
return fence('ts', body);
}
/** Headings inside a JSDoc body, demoted so they nest under the symbol's `##` heading. */
export function demoteHeadings(text: string): string {
let inFence = false;
return text
.split('\n')
.map((line) => {
if (/^\s*```/.test(line)) inFence = !inFence;
if (inFence) return line;
return line.replace(/^(#{1,4})(\s)/, (_match, hashes: string, space: string) => `${hashes}##${space}`);
})
.join('\n');
}
function docBody(doc: DocBlock): string {
const parts: string[] = [doc.text ? demoteHeadings(doc.text) : NO_DESCRIPTION];
for (const tag of doc.tags) {
if (tag.name === 'example') parts.push(exampleBlock(tag.text));
else parts.push(`**@${tag.name}**${tag.text ? ` ${tag.text}` : ''}`);
}
return parts.join('\n\n');
}
function docCell(doc: DocBlock): string {
return doc.text || NO_DESCRIPTION;
}
/** A type (or default) for a table cell: inline when short, else a reference to a block rendered under the table. */
class LongCells {
private readonly blocks: string[] = [];
cell(key: string, what: string, text: string, language = 'ts'): string {
if (text.length <= LONG_CELL) return code(text);
this.blocks.push(`${code(key)} ${what}:\n\n${fence(language, text)}`);
return `see ${what} below`;
}
render(): string {
return this.blocks.join('\n\n');
}
}
/** A default or initial value, led by what it means when its source names that in JSDoc. */
function valueCell(long: LongCells, key: string, what: string, value: DefaultValue): string {
const cell = long.cell(key, what, value.text);
return value.note ? `${value.note} (${cell})` : cell;
}
/** A collapsed block GitHub renders from `<details>`; the blank lines keep Markdown active inside it. */
function details(summary: string, parts: string[]): string {
return [`<details>`, `<summary>${summary}</summary>`, '', ...parts.flatMap((part) => [part, '']), '</details>'].join(
'\n'
);
}
function section(parts: (string | undefined)[]): string {
return parts.filter((part): part is string => !!part).join('\n\n');
}
// ── Behaviors ────────────────────────────────────────────────────────────────
function behaviorPage(info: BehaviorInfo): string | undefined {
return info.entry?.page;
}
/** A link to a behavior's heading, or to its source when it has no page (a behavior built inline in a feature). */
function behaviorLink(reference: ReferenceProgram, fromPage: string, info: BehaviorInfo): string {
const page = behaviorPage(info);
if (page) return link(fromPage, page, info.name, anchor(info.name));
return `${code(info.label)} (${sourceLink(reference, fromPage, info.file)})`;
}
function ownerCell(reference: ReferenceProgram, fromPage: string, row: SlotRow, pageFile: string): string {
if (!row.owner) return '—';
const name = row.owner.name ? code(row.owner.name) : 'inline';
if (row.owner.file === pageFile) return name;
const entry = reference.entries.find((candidate) => candidate.file === row.owner?.file);
const target = entry?.page ? link(fromPage, entry.page, entry.key) : sourceLink(reference, fromPage, row.owner.file);
return `${name} (${target})`;
}
function slotTable(
reference: ReferenceProgram,
model: Model,
fromPage: string,
info: BehaviorInfo,
slot: 'state' | 'context'
): string | undefined {
const rows = info[slot];
if (rows.length === 0) return undefined;
const declaredKeys = slot === 'state' ? info.stateKeys : info.contextKeys;
const long = new LongCells();
const declaredColumn = declaredKeys !== undefined;
const headers = ['Key', 'Access', ...(declaredColumn ? ['Declared'] : []), 'Type', 'Owner', 'Doc'];
const body = rows.map((row) => [
code(row.key),
row.access,
...(declaredColumn ? [row.declared ? 'yes' : row.optional ? 'reads if present' : 'no'] : []),
long.cell(row.key, 'type', row.type),
ownerCell(reference, fromPage, row, info.file),
row.doc.text ? docCell(row.doc) : borrowedDocCell(reference, fromPage, docPool(model), slot, row.key, [info]),
]);
return section([table(headers, body), long.render()]);
}
function configTable(rows: ConfigRow[]): string | undefined {
if (rows.length === 0) return undefined;
const long = new LongCells();
const body = rows.map((row) => [
code(row.optional ? `${row.key}?` : row.key),
long.cell(row.key, 'type', row.type),
docCell(row.doc),
]);
return section([table(['Key', 'Type', 'Doc'], body), long.render()]);
}
function behaviorSection(reference: ReferenceProgram, model: Model, page: string, info: BehaviorInfo): string {
const configNote =
info.configOptional === undefined
? undefined
: info.configOptional
? 'The setup declares `config?`: callers may omit it.'
: 'The setup declares `config` as required.';
const keysNote = [
info.stateKeys === undefined ? '`stateKeys` are not derivable from the type or the initializer.' : undefined,
info.contextKeys === undefined ? '`contextKeys` are not derivable from the type or the initializer.' : undefined,
].filter(Boolean);
const config = configTable(info.config);
const state = slotTable(reference, model, page, info, 'state');
const context = slotTable(reference, model, page, info, 'context');
return section([
`## ${info.name}`,
docBody(info.doc),
`Source: ${sourceLink(reference, page, info.file)}`,
keysNote.length ? keysNote.join(' ') : undefined,
config || configNote ? '### Config' : undefined,
config ? configNote : undefined,
config ?? (configNote ? `${configNote} It has no keys.` : undefined),
state ? '### State' : undefined,
state,
context ? '### Context' : undefined,
context,
]);
}
/**
* The module's exports that are not rendered as their own sections: name, kind, description, source. The description is
* what the model knows first — the behaviors a type is the config, state, or context of; the section of this page that
* lists a `Config` / `State` / `Context` type's keys; an object literal's source — then the JSDoc's first sentence,
* then what an undocumented type declares.
*/
function otherExports(
reference: ReferenceProgram,
model: Model,
page: string,
entry: EntryPoint,
rendered: Set<string>,
sections: Map<string, string> = new Map()
): string | undefined {
const { checker } = reference;
const long = new LongCells();
const rows: string[][] = [];
for (const exported of moduleExports(reference, entry.file)) {
if (rendered.has(exported.name)) continue;
const symbol = resolveAlias(checker, exported);
const file = declaringFile(symbol) ?? entry.file;
const doc = docOf(checker, symbol);
const roles = typeRoles(reference, model, page, { name: symbol.name, file });
const listed = sections.get(exported.name);
const literal = exportedLiteral(symbol);
const parts = [
roles,
firstSentence(doc),
listed ? `Listed under [${listed}](#${anchor(listed)}).` : undefined,
literal === '{}'
? `${EMPTY_VALUES.get(exported.name) ?? 'It is empty'} (\`{}\`).`
: literal
? `Its value: ${long.cell(exported.name, 'value', literal)}.`
: undefined,
].filter(Boolean);
rows.push([
code(exported.name),
exportKind(symbol),
parts.length ? parts.join(' ') : declaredTypeCell(long, exported.name, declaredTypeOf(checker, symbol)),
sourceLink(reference, page, file),
]);
}
if (rows.length === 0) return undefined;
rows.sort((a, b) => a[0]!.localeCompare(b[0]!));
const headers = ['Name', 'Kind', 'Description', 'Source'];
const parts = rows.filter((row) => !TYPE_KINDS.has(row[1]!));
const types = rows.filter((row) => TYPE_KINDS.has(row[1]!));
return section([
parts.length ? '## Other functions and constants' : undefined,
parts.length ? table(headers, parts) : undefined,
types.length ? '## Types' : undefined,
types.length ? table(headers, types) : undefined,
long.render(),
]);
}
/**
* Heads a Config table: its default column shows only what a feature's `defaultConfig` supplies, so a behavior's own
* fallback for an unset key is left to the key's doc.
*/
const FEATURE_DEFAULT_NOTE =
"Feature default is the value a feature's `defaultConfig` supplies. A behavior's own fallback for a key left unset is described under Doc.";
/** What an empty `defaultConfig` or `initialState` means, said in words instead of the bare `{}`. */
const EMPTY_VALUES = new Map([
['defaultConfig', 'It contributes none'],
['initialState', 'It seeds none'],
]);
/** Export kinds listed under "Types"; every other kind lists under "Other functions and constants". */
const TYPE_KINDS = new Set(['type', 'interface', 'enum']);
/**
* Which behaviors a named type serves as the config, state, or context type of, as "Config of [a], [b]" sentences;
* empty when none does.
*/
function typeRoles(reference: ReferenceProgram, model: Model, page: string, owner: Owner): string {
const sameOwner = (candidate: Owner | undefined) =>
!!candidate && candidate.name === owner.name && candidate.file === owner.file;
const pool = docPool(model);
const of = (label: string, behaviors: BehaviorInfo[]) =>
behaviors.length ? `${label} of ${behaviors.map((info) => behaviorLink(reference, page, info)).join(', ')}.` : '';
return [
of(
'Config',
pool.filter((info) => info.configTypes.some(sameOwner))
),
of(
'State',
pool.filter((info) => info.state.some((row) => !row.observed && sameOwner(row.owner)))
),
of(
'Context',
pool.filter((info) => info.context.some((row) => sameOwner(row.owner)))
),
]
.filter(Boolean)
.join(' ');
}
/** The description of a type export without JSDoc: what its declaration says it is. */
function declaredTypeCell(long: LongCells, name: string, declared: ReturnType<typeof declaredTypeOf>): string {
if (!declared) return NO_DESCRIPTION;
// `type Behaviors = typeof behaviors` names a value the page already describes; say so instead of quoting it.
const typeOf = declared.kind === 'alias' ? /^typeof ([A-Za-z_$][\w$]*)$/.exec(declared.text) : null;
if (typeOf) return `The type of ${code(typeOf[1])}.`;
if (declared.kind === 'alias') return `No JSDoc; an alias of ${long.cell(name, 'type', declared.text)}.`;
return declared.text
? `No JSDoc; fields ${long.cell(name, 'fields', declared.text, 'text')}.`
: 'No JSDoc; no fields.';
}
function renderBehaviorPage(reference: ReferenceProgram, model: Model, entry: EntryPoint): string {
const page = entry.page!;
// Source order: a module declares the behavior its siblings are described as variants of first.
const behaviors = model.behaviors.filter((info) => info.entry === entry);
const description = moduleDoc(reference, entry.file);
return section([
GENERATED_NOTICE,
`# ${code(entry.specifier)}`,
`Source: ${sourceLink(reference, page, entry.file)}`,
description ? docBody(description) : undefined,
...behaviors.map((info) => behaviorSection(reference, model, page, info)),
otherExports(reference, model, page, entry, new Set(behaviors.map((info) => info.name))),
]);
}
// ── Features and engines ─────────────────────────────────────────────────────
/** Behaviors among `behaviors` that read config key `key`, in composition order. */
function readersOf(behaviors: BehaviorInfo[], key: string): BehaviorInfo[] {
return behaviors.filter((info) => info.config.some((row) => row.key === key));
}
/**
* The config field doc for a key and the behavior it comes from: the first of `readers`, then of the rest of `pool`,
* whose doc does not defer to another type's field for the key, else the first reader's. A doc that points at
* `Type['key']` (`See …`, `Semantics on …`) leaves the key's meaning to that field, which another reader owns.
*/
function configDoc(
readers: BehaviorInfo[],
pool: BehaviorInfo[],
key: string
): { doc: DocBlock; from: BehaviorInfo } | undefined {
const pointer = new RegExp(`(?:[Ss]ee|Semantics on)\\s+\`\\w+\\['${key}'\\]\``);
const docs = [...readers, ...readersOf(pool, key).filter((info) => !readers.includes(info))].flatMap((from) => {
const doc = from.config.find((row) => row.key === key)?.doc;
return doc?.text ? [{ doc, from }] : [];
});
return docs.find(({ doc }) => !pointer.test(doc.text)) ?? docs[0];
}
/**
* A config key's doc cell, naming the behavior the doc comes from when it is not one of `readers`. An optional key, or
* one the page's feature supplies a default for, drops the doc's `**Required** — …` sentence, which holds for the
* behavior alone.
*/
function configDocCell(
reference: ReferenceProgram,
model: Model,
page: string,
readers: BehaviorInfo[],
key: string,
optional: boolean
): string {
const found = configDoc(readers, docPool(model), key);
if (!found) return NO_DESCRIPTION;
const text = optional ? found.doc.text.replace(/\s*\*\*Required\*\*\s+—.*?\.(?=\s|$)/s, '') : found.doc.text;
const lender = readers.includes(found.from) ? '' : ` (documented on ${behaviorLink(reference, page, found.from)})`;
return `${docCell({ ...found.doc, text })}${lender}`;
}
function slotOf(info: BehaviorInfo, slot: 'state' | 'context', key: string): SlotRow | undefined {
return info[slot].find((row) => row.key === key);
}
/** The slot doc from the first behavior that writes the key, else the first that reads it, and which behavior. */
function slotDoc(
behaviors: BehaviorInfo[],
slot: 'state' | 'context',
key: string
): { doc: DocBlock; from: BehaviorInfo } | undefined {
const rows = behaviors
.map((info) => ({ info, row: slotOf(info, slot, key) }))
.filter((pair): pair is { info: BehaviorInfo; row: SlotRow } => !!pair.row);
const documented = [
...rows.filter(({ row }) => row.access === 'writes'),
...rows.filter(({ row }) => row.access === 'reads'),
];
const found = documented.find(({ row }) => row.doc.text);
return found ? { doc: found.row.doc, from: found.info } : undefined;
}
/**
* Every behavior a slot doc can be borrowed from: the exported ones, then those built inline in a feature's list (the
* external-signal declarations among them carry the docs of the keys no behavior declares).
*/
function docPool(model: Model): BehaviorInfo[] {
return [...new Set([...model.behaviors, ...model.features.flatMap((feature) => feature.behaviors)])];
}
/**
* The doc cell for a key none of `own` documents: the doc `slotDoc` finds among `behaviors`, naming the behavior it
* comes from when that behavior is not one of `own`.
*/
function borrowedDocCell(
reference: ReferenceProgram,
page: string,
behaviors: BehaviorInfo[],
slot: 'state' | 'context',
key: string,
own: BehaviorInfo[]
): string {
const found = slotDoc(behaviors, slot, key);
if (!found) return NO_DESCRIPTION;
const lender = own.includes(found.from) ? '' : ` (documented on ${behaviorLink(reference, page, found.from)})`;
return `${docCell(found.doc)}${lender}`;
}
function behaviorLinks(reference: ReferenceProgram, page: string, behaviors: BehaviorInfo[]): string {
return behaviors.length ? behaviors.map((info) => behaviorLink(reference, page, info)).join(', ') : '—';
}
/**
* A key's `initialState` entry and the feature that supplies it; a later feature's entry replaces an earlier one's, and
* an engine's own entry (no `feature`) replaces them all.
*/
function initialOf(
features: FeatureInfo[],
key: string,
engineInitial: DefaultValue[]
): { value: DefaultValue; feature?: FeatureInfo } | undefined {
const own = engineInitial.find((candidate) => candidate.key === key);
if (own) return { value: own };
const feature = [...features].reverse().find((candidate) => candidate.initial.some((value) => value.key === key));
const value = feature?.initial.find((candidate) => candidate.key === key);
return feature && value ? { value, feature } : undefined;
}
/**
* The state or context keys of a feature or engine. A state table also shows each key's `initialState` value from
* `features`, or from the engine's own `engineInitial`, and, when more than one feature could supply it, which one
* does.
*/
function slotFieldsTable(
reference: ReferenceProgram,
model: Model,
page: string,
fields: TypeField[],
behaviors: BehaviorInfo[],
slot: 'state' | 'context',
features: FeatureInfo[] = [],
engineInitial: DefaultValue[] = []
): string | undefined {
if (fields.length === 0) return undefined;
const long = new LongCells();
const initialColumns = slot === 'state' ? ['Initial', ...(features.length > 1 ? ['Initial from'] : [])] : [];
const rows = fields.map((field) => {
const declaredBy = behaviors.filter((info) => !info.external && slotOf(info, slot, field.key)?.declared);
const external = behaviors.some((info) => info.external && slotOf(info, slot, field.key)?.declared);
const initial = slot === 'state' ? initialOf(features, field.key, engineInitial) : undefined;
return [
code(field.optional ? `${field.key}?` : field.key),
long.cell(field.key, 'type', field.type),
...(initialColumns.length ? [initial ? valueCell(long, field.key, 'initial', initial.value) : '—'] : []),
...(initialColumns.length > 1
? [initial?.feature ? link(page, initial.feature.entry.page!, initial.feature.name) : initial ? 'engine' : '—']
: []),
[
...(external ? ['[external signal](#external-signals)'] : []),
...(declaredBy.length ? [behaviorLinks(reference, page, declaredBy)] : []),
].join(', ') || '—',
borrowedDocCell(reference, page, [...behaviors, ...docPool(model)], slot, field.key, behaviors),
];
});
return section([table(['Key', 'Type', ...initialColumns, 'Declared by', 'Doc'], rows), long.render()]);
}
/**
* The state keys a feature (or an engine, through its features) declares to be written from outside the engine, as a
* section: what they are, how they get written, then one row per key with its type and its doc. The doc names the
* reader; the selection rules read these keys through optional deps the model does not see, so a "Read by" column would
* mislead.
*/
function externalSignalsSection(
reference: ReferenceProgram,
model: Model,
page: string,
behaviors: BehaviorInfo[],
fields: TypeField[],
features: FeatureInfo[] = []
): string | undefined {
const declarations = behaviors.filter((info) => info.external);
if (declarations.length === 0) return undefined;
const long = new LongCells();
const fromColumn = features.length > 1;
const rows = declarations.flatMap((declaration) =>
(declaration.stateKeys ?? []).map((key) => {
const field = fields.find((candidate) => candidate.key === key);
const from = features.find((feature) => feature.behaviors.includes(declaration));
return [
code(key),
field ? long.cell(key, 'type', field.type) : '—',
...(fromColumn ? [from ? link(page, from.entry.page!, from.name) : '—'] : []),
borrowedDocCell(reference, page, [...behaviors, ...docPool(model)], 'state', key, behaviors),
];
})
);
const who =
features.length > 1 ? "The engine's features declare these state keys" : 'The feature declares these state keys';
const lead = `${who} for code outside the engine to write; no behavior sets them. The SPF Medias write them from their own properties, and code driving an engine directly writes \`engine.state.<key>.set(value)\`. Each is declared with ${link(page, 'core/define-external-signals.md', 'defineExternalSignals', 'defineexternalsignals')}, which is what makes the key part of the engine's state type.`;
return section([lead, table(['Key', 'Type', ...(fromColumn ? ['From'] : []), 'Doc'], rows), long.render()]);
}
/**
* The behaviors a feature's config key is for: the feature's own readers in composition order. A key the feature's
* `defaultConfig` supplies adds the behaviors the literal's `satisfies` type names (the declarations behind the key),
* alphabetical, or every behavior that reads it when no `satisfies` clause covers it.
*/
function defaultReaders(model: Model, feature: FeatureInfo, key: string): BehaviorInfo[] {
const own = readersOf(feature.behaviors, key);
const value = feature.defaults.find((candidate) => candidate.key === key);
if (!value) return own;
const declared = new Set(value.readerDeclarations);
const others = readersOf(model.behaviors, key)
.filter((info) => !own.includes(info))
.filter(
(info) =>
declared.size === 0 ||
info.config.some((row) => row.key === key && row.declarations.some((declaration) => declared.has(declaration)))
)
.sort((a, b) => a.name.localeCompare(b.name));
return [...own, ...others];
}
function featureConfigTable(
reference: ReferenceProgram,
model: Model,
page: string,
feature: FeatureInfo
): string | undefined {
const keys = [...new Set([...feature.config.map((f) => f.key), ...feature.defaults.map((d) => d.key)])].sort();
if (keys.length === 0) return undefined;
const long = new LongCells();
const rows = keys.map((key) => {
const field = feature.config.find((candidate) => candidate.key === key);
const value = feature.defaults.find((candidate) => candidate.key === key);
const readers = defaultReaders(model, feature, key);
const type = field?.type ?? value?.type ?? readers[0]?.config.find((row) => row.key === key)?.type;
return [
code(field ? (field.optional ? `${key}?` : key) : key),
type ? long.cell(key, 'type', type) : '—',
value ? valueCell(long, key, 'default', value) : '—',
behaviorLinks(reference, page, readers),
configDocCell(reference, model, page, readers, key, value !== undefined || Boolean(field?.optional)),
];
});
return section([
FEATURE_DEFAULT_NOTE,
table(['Key', 'Type', 'Feature default', 'Read by', 'Doc'], rows),
long.render(),
]);
}
function renderFeaturePage(reference: ReferenceProgram, model: Model, feature: FeatureInfo): string {
const page = feature.entry.page!;
// A behavior built inline in the feature's list is shown as written, since this page is where it is defined.
const listed = feature.behaviors.filter((info) => !info.external);
const behaviors = listed.length
? listed
.map((info, index) => `${index + 1}. ${info.exported ? behaviorLink(reference, page, info) : code(info.name)}`)
.join('\n')
: 'None.';
const externalSignals = externalSignalsSection(reference, model, page, feature.behaviors, feature.state);
const config = featureConfigTable(reference, model, page, feature);
const state = slotFieldsTable(reference, model, page, feature.state, feature.behaviors, 'state', [feature]);
const context = slotFieldsTable(reference, model, page, feature.context, feature.behaviors, 'context');
const sections = new Map([
['behaviors', 'Behaviors'],
...(config ? [['Config', 'Config'] as const] : []),
...(state ? [['State', 'State'] as const] : []),
...(context ? [['Context', 'Context'] as const] : []),
]);
const composedBy = feature.composedBy.length
? feature.composedBy.map((engine) => `- ${link(page, engine.entry.page!, engine.entry.specifier)}`).join('\n')
: 'None.';
return section([
GENERATED_NOTICE,
`# ${code(feature.entry.specifier)}`,
`Source: ${sourceLink(reference, page, feature.file)}`,
`## ${feature.name}`,
docBody(feature.doc),
'### Behaviors',
behaviors,
externalSignals ? '### External signals' : undefined,
externalSignals,
config ? '### Config' : undefined,
config,
state ? '### State' : undefined,
state,
context ? '### Context' : undefined,
context,
'### Composed by',
composedBy,
otherExports(reference, model, page, feature.entry, new Set([feature.name]), sections),
]);
}
function engineConfigTable(
reference: ReferenceProgram,
model: Model,
page: string,
engine: EngineInfo
): string | undefined {
if (engine.config.length === 0) return undefined;
const long = new LongCells();
const rows = engine.config.map((field) => {
// A later feature's `defaultConfig` key replaces an earlier one's.
const supplier = [...engine.features]
.reverse()
.find((feature) => feature.defaults.some((value) => value.key === field.key));
const value = supplier?.defaults.find((candidate) => candidate.key === field.key);
const readers = readersOf(engine.behaviors, field.key);
return [
code(field.optional ? `${field.key}?` : field.key),
long.cell(field.key, 'type', field.type),
value ? valueCell(long, field.key, 'default', value) : '—',
supplier ? link(page, supplier.entry.page!, supplier.name) : '—',
behaviorLinks(reference, page, readers),
configDocCell(reference, model, page, readers, field.key, field.optional),
];
});
return section([
FEATURE_DEFAULT_NOTE,
table(['Key', 'Type', 'Feature default', 'Default from', 'Read by', 'Doc'], rows),
long.render(),
]);
}
function renderEnginePage(reference: ReferenceProgram, model: Model, engine: EngineInfo): string {
const page = engine.entry.page!;
const features = engine.features
.map((feature, index) => `${index + 1}. ${link(page, feature.entry.page!, feature.name)}`)
.join('\n');
const behaviors = engine.behaviors
.filter((info) => !info.external)
.map((info, index) => `${index + 1}. ${behaviorLink(reference, page, info)}`)
.join('\n');
const externalSignals = externalSignalsSection(
reference,
model,
page,
engine.behaviors,
engine.state,
engine.features
);
const config = engineConfigTable(reference, model, page, engine);
const state = slotFieldsTable(
reference,
model,
page,
engine.state,
engine.behaviors,
'state',
engine.features,
engine.initial
);
const context = slotFieldsTable(reference, model, page, engine.context, engine.behaviors, 'context');
const sections = new Map([
['features', 'Features'],
['behaviors', 'Behaviors'],
...(config ? [['EngineConfig', 'Config'] as const] : []),
...(state ? [['EngineState', 'State'] as const] : []),
...(context ? [['EngineContext', 'Context'] as const] : []),
]);
return section([
GENERATED_NOTICE,
`# ${code(engine.entry.specifier)}`,
`Source: ${sourceLink(reference, page, engine.file)}`,
'## createEngine',
docBody(engine.doc),
'### Features',
features,
'### Behaviors',
behaviors,
externalSignals ? '### External signals' : undefined,
externalSignals,
config ? '### Config' : undefined,
config,
state ? '### State' : undefined,
state,
context ? '### Context' : undefined,
context,
otherExports(reference, model, page, engine.entry, new Set(['createEngine']), sections),
]);
}
// ── Core ─────────────────────────────────────────────────────────────────────
interface CoreModule {
/** The module name, e.g. `define-behavior`. */
name: string;
page: string;
file: string;
/** Export names the root entry re-exports from the module, alphabetical. */
exports: string[];
}
/** The root entry's re-exports from `src/core/composition/`, grouped by module. */
function coreModules(reference: ReferenceProgram): CoreModule[] {
const root = reference.entries.find((entry) => entry.key === 'index');
if (!root) throw new Error('No `index` entry');
const sourceFile = reference.program.getSourceFile(root.file);
if (!sourceFile) throw new Error(`Not in the program: ${root.file}`);
const modules = new Map<string, CoreModule>();
for (const statement of sourceFile.statements) {
if (!ts.isExportDeclaration(statement) || !statement.moduleSpecifier) continue;
if (!ts.isStringLiteralLike(statement.moduleSpecifier)) continue;
const specifier = statement.moduleSpecifier.text;
if (!specifier.startsWith(CORE_MODULE_PREFIX)) continue;
const name = specifier.slice(CORE_MODULE_PREFIX.length);
const module = modules.get(name) ?? {
name,
page: `core/${name}.md`,
file: `${dirname(root.file)}/core/composition/${name}.ts`,
exports: [],
};
modules.set(name, module);
const clause = statement.exportClause;
if (clause && ts.isNamedExports(clause)) {
for (const element of clause.elements) module.exports.push(element.name.text);
}
}
for (const module of modules.values()) module.exports.sort();
return [...modules.values()].sort((a, b) => CORE_MODULE_ORDER.indexOf(a.name) - CORE_MODULE_ORDER.indexOf(b.name));
}
/** The composition modules in dependency order: a behavior, the signals written from outside, a feature, a composition. */
const CORE_MODULE_ORDER = ['define-behavior', 'define-external-signals', 'define-feature', 'create-composition'];
function renderCorePage(reference: ReferenceProgram, module: CoreModule): string {
const { checker } = reference;
const exports = new Map(moduleExports(reference, module.file).map((symbol) => [symbol.name, symbol]));
const sections = module.exports.map((name) => {
const symbol = exports.get(name);
if (!symbol) throw new Error(`${module.file} does not export \`${name}\``);
const resolved = resolveAlias(checker, symbol);
const signature = declarationSignature(resolved);
return section([
`## ${name}`,
docBody(docOf(checker, resolved)),
signature ? fence('ts', signature) : undefined,
`Source: ${sourceLink(reference, module.page, declaringFile(resolved) ?? module.file)}`,
]);
});
const description = moduleDoc(reference, module.file);
return section([
GENERATED_NOTICE,
`# ${code(reference.packageName)}: ${module.name}`,
`Exports of ${code(reference.packageName)} declared in ${sourceLink(reference, module.page, module.file)}.`,
description ? docBody(description) : undefined,
...sections,
]);
}
// ── README ───────────────────────────────────────────────────────────────────
/** Fill and stroke pairs for engine boxes and their arrows, readable on GitHub's light and dark Mermaid themes. */
const ENGINE_COLORS = [
{ fill: '#2563eb', stroke: '#1d4ed8' },
{ fill: '#d97706', stroke: '#b45309' },
{ fill: '#16a34a', stroke: '#15803d' },
{ fill: '#9333ea', stroke: '#7e22ce' },
{ fill: '#dc2626', stroke: '#b91c1c' },
];
/** Features per row inside a diagram group, so a large group wraps into a block instead of running off the page. */
const DIAGRAM_ROW = 5;
/**
* Engines and features as a Mermaid flowchart, left to right: engines in a column on the left, groups of features on
* the right. Features are grouped by the set of engines that compose them, so an engine draws one arrow per group
* rather than one per feature, and each engine's box and arrows share a color. Within a group, features keep the
* composition order of the first engine that lists them, chained with invisible links (`~~~`) into rows of
* `DIAGRAM_ROW`; a group with internal links honors its own `direction`, which is what keeps the rows horizontal.
* Invisible links are edges too, so they count toward the `linkStyle` indices.
*/
function mermaid(model: Model): string {
const id = (prefix: string, name: string) => `${prefix}_${name.replace(/[^\w]/g, '_')}`;
const color = (index: number) => ENGINE_COLORS[index % ENGINE_COLORS.length]!;
const groups = new Map<string, { engines: EngineInfo[]; features: FeatureInfo[] }>();
for (const feature of model.features) {
const engines = model.engines.filter((engine) => engine.features.includes(feature));
const key = engines.map((engine) => engine.name).join('+') || '-';
const group = groups.get(key) ?? { engines, features: [] };
group.features.push(feature);
groups.set(key, group);
}
// Read from the first engine down: its own features, then the ones it shares with the next engine, and so on.
const ordered = [...groups.values()].sort(
(a, b) =>
model.engines.indexOf(a.engines[0]!) - model.engines.indexOf(b.engines[0]!) || a.engines.length - b.engines.length
);
const label = (engines: EngineInfo[]) => {
if (engines.length === 0) return 'no engine';
if (engines.length === model.engines.length) return 'every engine';
return engines.length === 1 ? `${engines[0]!.name} only` : engines.map((engine) => engine.name).join(' and ');
};
const lines = ['graph LR'];
let edge = 0;
model.engines.forEach((engine, index) => {
const { fill, stroke } = color(index);
lines.push(` classDef ${id('engine', engine.name)} fill:${fill},stroke:${stroke},color:#fff`);
lines.push(` ${id('engine', engine.name)}["${engine.entry.specifier}"]:::${id('engine', engine.name)}`);
});
ordered.forEach((group, index) => {
const features = group.engines[0]
? group.engines[0].features.filter((feature) => group.features.includes(feature))
: group.features;
const nodes = features.map((feature) => id('feature', feature.entry.name));
lines.push(` subgraph group_${index}["${label(group.engines)}"]`);
lines.push(' direction LR');
for (const feature of features) lines.push(` ${id('feature', feature.entry.name)}["${feature.name}"]`);
for (let start = 0; start < nodes.length; start += DIAGRAM_ROW) {
const row = nodes.slice(start, start + DIAGRAM_ROW);
if (row.length < 2) continue;
lines.push(` ${row.join(' ~~~ ')}`);
edge += row.length - 1;
}
lines.push(' end');
});
model.engines.forEach((engine, index) => {
ordered.forEach((group, groupIndex) => {
if (!group.engines.includes(engine)) return;
lines.push(` ${id('engine', engine.name)} --> group_${groupIndex}`);
lines.push(` linkStyle ${edge} stroke:${color(index).fill},stroke-width:2px`);
edge += 1;
});
});
return fence('mermaid', lines.join('\n'));
}
/** A first sentence for an index cell: the emphasis a bold lead carries on its page says nothing in a table. */
function plainSentence(doc: DocBlock): string {
return firstSentence(doc).replace(/\*\*/g, '');
}
function renderReadme(reference: ReferenceProgram, model: Model, core: CoreModule[]): string {
const { checker } = reference;
const page = 'README.md';
const uncovered = reference.entries
.filter((entry) => !entry.layer && entry.key !== 'index')
.map((entry) => code(entry.specifier));
const coreSections = core.flatMap((module) => {
const exports = new Map(moduleExports(reference, module.file).map((symbol) => [symbol.name, symbol]));
const rows = module.exports.map((name) => {
const symbol = resolveAlias(checker, exports.get(name)!);
return [
link(page, module.page, code(name), anchor(name)),
exportKind(symbol),
plainSentence(docOf(checker, symbol)) || NO_DESCRIPTION,
];
});
const values = rows.filter((row) => !TYPE_KINDS.has(row[1]!));
const types = rows.filter((row) => TYPE_KINDS.has(row[1]!));
const description = moduleDoc(reference, module.file);
return [
`### ${link(page, module.page, module.name)}`,
description ? plainSentence(description) : undefined,
table(['Export', 'Kind', 'Description'], [...values, ...types]),
];
});
const engineRows = model.engines.map((engine) => [
code(engine.entry.specifier),
link(page, engine.entry.page!, engine.name),
plainSentence(engine.doc) || NO_DESCRIPTION,
]);
const featureRows = model.features.map((feature) => [
code(feature.name),
link(page, feature.entry.page!, feature.entry.name),
plainSentence(feature.doc) || NO_DESCRIPTION,
]);
// Behavior pages in the order the first engine composes them (its page lists the same order), then the pages no
// shipped engine composes, alphabetically. A page's description is its module description, else its behavior's.
const pipeline = model.engines[0]?.behaviors ?? [];
const pagesInOrder = () => {
const pages = new Map<string, { entry: EntryPoint; behaviors: BehaviorInfo[] }>();
const register = (info: BehaviorInfo) => {
if (info.entry?.layer !== 'behavior' && info.entry?.layer !== 'behavior-dom') return;
const group = pages.get(info.entry.page!) ?? { entry: info.entry, behaviors: [] };
if (!group.behaviors.includes(info)) group.behaviors.push(info);
pages.set(info.entry.page!, group);
};
for (const info of pipeline) register(info);
for (const info of [...model.behaviors].sort((a, b) => a.name.localeCompare(b.name))) register(info);
return [...pages.values()];
};
const behaviorRows = pagesInOrder().map(({ entry, behaviors }) => {
const description = moduleDoc(reference, entry.file) ?? behaviors[0]!.doc;
return [
behaviors.map((info) => link(page, entry.page!, info.name, anchor(info.name))).join(', '),
link(page, entry.page!, code(entry.specifier)),
entry.layer === 'behavior-dom' ? 'yes' : '—',
plainSentence(description) || NO_DESCRIPTION,
];
});
const engineHeaders = ['Entry point', 'Page', 'Description'];
const featureHeaders = ['Feature', 'Page', 'Description'];
const behaviorHeaders = ['Behaviors', 'Entry point', 'DOM', 'Description'];
const counts = {
core: core.reduce((total, module) => total + module.exports.length, 0),
engines: model.engines.length,
features: model.features.length,
behaviors: model.behaviors.filter((info) => info.entry).length,
};
return section([
GENERATED_NOTICE,
`# ${code(reference.packageName)} API reference`,
`${code(reference.packageName)} builds a playback engine by composing behaviors, grouped into features. This reference covers ${counts.engines} engines, the ${counts.features} features they compose, the ${counts.behaviors} behaviors the behavior entry points export, and the ${counts.core} composition exports that put them together. Each engine page lists its features and behaviors in composition order with the config, state, and context keys they resolve to; each feature page does the same for its behaviors; each behavior page shows what its setup reads and writes.`,
'## Engines and features',
"Each engine's box and arrows share a color. Features are grouped by which engines compose them; each engine page lists its own features in composition order.",
mermaid(model),
'## Engines',
table(engineHeaders, engineRows),
'## Features',
table(featureHeaders, featureRows),
'## Behaviors',
'One row per entry point, in the order the first engine composes them; a module that exports several behaviors lists them all. "DOM" marks the behaviors that need a browser: they drive a media element, a `MediaSource`, or `MediaKeys`, and ship under `behaviors/dom/`.',
table(behaviorHeaders, behaviorRows),
'## Composition',
'The four modules that turn behaviors into an engine, in the order they build on each other. Functions first, then the types each exports.',
...coreSections,
details('How this reference is generated', [
`Generated from the TypeScript sources and their JSDoc by \`scripts/build-reference.ts\`. It covers the composition factories the root entry exports from \`src/core/composition/\`, the playback engines (\`${reference.packageName}/engines/*\`), their features (\`${reference.packageName}/features/*\`), and the behaviors (\`${reference.packageName}/behaviors/*\`). It does not cover the root entry's other exports, nor these entry points: ${uncovered.join(', ')}.`,
'Regenerate with `pnpm -F @videojs/spf docs:reference`; `pnpm -F @videojs/spf docs:reference:check` fails when the committed output is stale.',
'A feature page lists the state keys it declares to be written from outside the engine under "External signals", apart from its behaviors; an engine page collects its features\' under the same heading.',
"A behavior page opens with its module description when the source file starts with a JSDoc block set off from the imports by a blank line; the README uses that description for the page, else the first behavior's. Each page lists its remaining exports as Other functions and constants, and Types.",
'A behavior without JSDoc shows the JSDoc of the function its `setup` names; a type export without JSDoc shows what its declaration says it is; a symbol with no doc anywhere reads "No description."',
'A config key\'s doc is the config field JSDoc of the first behavior listed under "Read by" that has one. A state or context key\'s doc is the field JSDoc of the first behavior that writes the key, else the first that reads it; where that behavior is not on the page, the cell says which one it is documented on.',
]),
]);
}
// ── Entry ────────────────────────────────────────────────────────────────────
export function renderPages(reference: ReferenceProgram, model: Model): Pages {
const pages: Pages = new Map();
const core = coreModules(reference);
pages.set('README.md', renderReadme(reference, model, core));
for (const module of core) pages.set(module.page, renderCorePage(reference, module));
for (const entry of reference.entries) {
if (entry.layer === 'behavior' || entry.layer === 'behavior-dom') {
pages.set(entry.page!, renderBehaviorPage(reference, model, entry));
}
}
for (const feature of model.features) pages.set(feature.entry.page!, renderFeaturePage(reference, model, feature));
for (const engine of model.engines) pages.set(engine.entry.page!, renderEnginePage(reference, model, engine));
for (const [path, content] of pages) pages.set(path, `${content.replace(/\r\n/g, '\n').trimEnd()}\n`);
return pages;
}