File size: 9,922 Bytes
90219c5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | const localeCompare = require('@isaacs/string-locale-compare')('en')
const { join, basename, resolve } = require('path')
const transformHTML = require('./transform-html.js')
const { version } = require('../../lib/npm.js')
const { aliases } = require('../../lib/utils/cmd-list')
const { shorthands, definitions } = require('@npmcli/config/lib/definitions')
const DOC_EXT = '.md'
const TAGS = {
CONFIG: '<!-- AUTOGENERATED CONFIG DESCRIPTIONS -->',
USAGE: '<!-- AUTOGENERATED USAGE DESCRIPTIONS -->',
SHORTHANDS: '<!-- AUTOGENERATED CONFIG SHORTHANDS -->',
}
const assertPlaceholder = (src, path, placeholder) => {
if (!src.includes(placeholder)) {
throw new Error(
`Cannot replace ${placeholder} in ${path} due to missing placeholder`
)
}
return placeholder
}
// Default command loader - loads commands from lib/commands
const defaultCommandLoader = (name) => {
return require(`../../lib/commands/${name}`)
}
// Load a command using the provided loader or default
const getCommand = (name, commandLoader = defaultCommandLoader) => {
return commandLoader(name)
}
// Resolve definitions for a command - use definitions if present, otherwise build from params
const resolveDefinitions = (command) => {
// If command has definitions, use them directly (ignore params)
if (command.definitions && Object.keys(command.definitions).length > 0) {
return command.definitions
}
// Otherwise build from params using global definitions
if (command.params) {
const resolved = {}
for (const param of command.params) {
if (definitions[param]) {
resolved[param] = definitions[param]
}
}
return resolved
}
return {}
}
const getCommandByDoc = (docFile, docExt, commandLoader = defaultCommandLoader) => {
// Grab the command name from the *.md filename
// NOTE: We cannot use the name property command file because in the case of
// `npx` the file being used is `lib/commands/exec.js`
const name = basename(docFile, docExt).replace('npm-', '')
if (name === 'npm') {
return {
name,
definitions: [],
usage: 'npm',
}
}
// special case for `npx`:
// `npx` is not technically a command in and of itself,
// so it just needs the usage of npm exec
const srcName = name === 'npx' ? 'exec' : name
const command = getCommand(srcName, commandLoader)
const { usage = [''], workspaces } = command
const usagePrefix = name === 'npx' ? 'npx' : `npm ${name}`
// Resolve definitions - handles exclusive params expansion
const commandDefs = resolveDefinitions(command)
const resolvedDefs = {}
for (const [key, def] of Object.entries(commandDefs)) {
resolvedDefs[key] = def
// Handle exclusive params
if (def.exclusive) {
for (const e of def.exclusive) {
if (!resolvedDefs[e] && definitions[e]) {
resolvedDefs[e] = definitions[e]
}
}
}
}
return {
name,
workspaces,
definitions: name === 'npx' ? {} : resolvedDefs,
usage: usage?.map(u => `${usagePrefix} ${u}`.trim()).join('\n'),
}
}
const replaceVersion = (src) => src.replace(/@VERSION@/g, version)
const replaceUsage = (src, { path, commandLoader }) => {
const replacer = assertPlaceholder(src, path, TAGS.USAGE)
const { usage, name, workspaces } = getCommandByDoc(path, DOC_EXT, commandLoader)
const synopsis = []
if (usage) {
synopsis.push('```bash', usage)
const cmdAliases = Object.keys(aliases).reduce((p, c) => {
if (aliases[c] === name) {
p.push(c)
}
return p
}, [])
if (cmdAliases.length === 1) {
synopsis.push('', `alias: ${cmdAliases[0]}`)
} else if (cmdAliases.length > 1) {
synopsis.push('', `aliases: ${cmdAliases.join(', ')}`)
}
synopsis.push('```')
}
if (!workspaces) {
if (synopsis.length) {
synopsis.push('')
}
synopsis.push('Note: This command is unaware of workspaces.')
}
return src.replace(replacer, synopsis.join('\n'))
}
// Helper to generate a markdown table from definitions
const generateFlagsTable = (definitionPool) => {
const rows = Object.keys(definitionPool).map((n) => {
const def = definitionPool[n]
const flags = [`\`--${def.key}\``]
if (def.alias) {
flags.push(...def.alias.map(a => `\`--${a}\``))
}
if (def.short) {
flags.push(`\`-${def.short}\``)
}
const flagsStr = flags.join(', ')
let defaultVal = def.defaultDescription
if (!defaultVal) {
defaultVal = String(def.default)
}
let typeVal = def.typeDescription || String(def.type)
if (def.required) {
typeVal = `${typeVal} (required)`
}
const desc = (def.description || '').replace(/\n/g, ' ').trim()
return `| ${flagsStr} | ${defaultVal} | ${typeVal} | ${desc} |`
})
return [
'| Flag | Default | Type | Description |',
'| --- | --- | --- | --- |',
...rows,
].join('\n')
}
const replaceDefinitions = (src, { path, commandLoader }) => {
const { definitions: commandDefs, name } = getCommandByDoc(path, DOC_EXT, commandLoader)
let subcommands = {}
try {
const command = getCommand(name, commandLoader)
subcommands = command.subcommands || {}
} catch {
// Command doesn't exist
}
// If no definitions and no subcommands, nothing to replace
if (Object.keys(commandDefs).length === 0 && Object.keys(subcommands).length === 0) {
return src
}
// Assert placeholder is present
const replacer = assertPlaceholder(src, path, TAGS.CONFIG)
// If command has subcommands, generate sections for each subcommand
if (Object.keys(subcommands).length > 0) {
const subcommandSections = Object.entries(subcommands).map(([subName, SubCommand]) => {
const subUsage = SubCommand.usage || []
const subDefs = resolveDefinitions(SubCommand)
const parts = [`### \`npm ${name} ${subName}\``, '']
if (SubCommand.description) {
parts.push(SubCommand.description, '')
}
// Add usage/synopsis
if (subUsage.length > 0) {
parts.push('#### Synopsis', '', '```bash')
subUsage.forEach(u => {
parts.push(`npm ${name} ${subName} ${u}`.trim())
})
parts.push('```', '')
}
// Add flags section if definitions exist
if (Object.keys(subDefs).length > 0) {
parts.push('#### Flags', '')
parts.push(generateFlagsTable(subDefs), '')
}
return parts.join('\n')
})
return src.replace(replacer, subcommandSections.join('\n'))
}
// For commands without subcommands - commandDefs must be non-empty here
// (we would have returned early at line 175 if both were empty)
const paramDescriptions = Object.values(commandDefs)
.map(def => def.describe())
return src.replace(replacer, paramDescriptions.join('\n\n'))
}
const replaceConfig = (src, { path }) => {
const replacer = assertPlaceholder(src, path, TAGS.CONFIG)
// sort not-deprecated ones to the top
/* istanbul ignore next - typically already sorted in the definitions file,
* but this is here so that our help doc will stay consistent if we decide
* to move them around. */
const sort = ([keya, { deprecated: depa }], [keyb, { deprecated: depb }]) => {
return depa && !depb ? 1
: !depa && depb ? -1
: localeCompare(keya, keyb)
}
const allConfig = Object.entries(definitions).sort(sort)
.map(([, def]) => def.describe())
.join('\n\n')
return src.replace(replacer, allConfig)
}
const replaceShorthands = (src, { path }) => {
const replacer = assertPlaceholder(src, path, TAGS.SHORTHANDS)
const sh = Object.entries(shorthands)
.sort(([shorta, expansiona], [shortb, expansionb]) =>
// sort by what they're short FOR
localeCompare(expansiona.join(' '), expansionb.join(' ')) || localeCompare(shorta, shortb)
)
.map(([short, expansion]) => {
// XXX: this is incorrect. we have multicharacter flags like `-iwr` that
// can only be set with a single dash
const dash = short.length === 1 ? '-' : '--'
return `* \`${dash}${short}\`: \`${expansion.join(' ')}\``
})
return src.replace(replacer, sh.join('\n'))
}
const replaceHelpLinks = (src) => {
// replaces markdown links with equivalent-ish npm help commands
return src.replace(
/\[`?([\w\s-]+)`?\]\(\/(?:commands|configuring-npm|using-npm)\/(?:[\w\s-]+)\)/g,
(_, p1) => {
const term = p1.replace(/npm\s/g, '').replace(/\s+/g, ' ').trim()
const help = `npm help ${term.includes(' ') ? `"${term}"` : term}`
return help
}
)
}
const transformMan = (src, { data, unified, remarkParse, remarkMan }) => unified()
.use(remarkParse)
.use(remarkMan, { version: `NPM@${version}` })
.processSync(`# ${data.title}(${data.section}) - ${data.description}\n\n${src}`)
.toString()
const manPath = (name, { data }) => join(`man${data.section}`, `${name}.${data.section}`)
const transformMd = (src, { frontmatter }) => ['---', frontmatter, '---', '', src].join('\n')
module.exports = {
DOC_EXT,
TAGS,
paths: {
content: resolve(__dirname, 'content'),
nav: resolve(__dirname, 'content', 'nav.yml'),
template: resolve(__dirname, 'template.html'),
man: resolve(__dirname, '..', '..', 'man'),
html: resolve(__dirname, '..', 'output'),
md: resolve(__dirname, '..', 'content'),
},
usage: replaceUsage,
definitions: replaceDefinitions,
config: replaceConfig,
shorthands: replaceShorthands,
version: replaceVersion,
helpLinks: replaceHelpLinks,
man: transformMan,
manPath: manPath,
md: transformMd,
html: transformHTML,
}
|