mdat 3.2.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib/index.js CHANGED
@@ -1,1232 +1,3 @@
1
- import { remark } from "remark";
2
- import remarkGfm from "remark-gfm";
3
- import { getSoleRule, mdatCollapse, mdatDiff, mdatExpand, mdatSplit, mdatStrip, rulesSchema, setLogger as setLogger$1 } from "remark-mdat";
4
- import { cosmiconfig, defaultLoaders } from "cosmiconfig";
5
- import { TypeScriptLoader } from "cosmiconfig-typescript-loader";
6
- import fs from "node:fs/promises";
7
- import path from "node:path";
8
- import picocolors from "picocolors";
9
- import plur from "plur";
10
- import { deepmerge } from "deepmerge-ts";
11
- import { createLogger, getChildLogger, injectionHelper } from "lognow";
12
- import { defineTemplate, getMetadata, helpers, setLogger as setLogger$2, templates } from "metascope";
13
- import { z } from "zod";
14
- import { globby } from "globby";
15
- import { isFile, isFileSync } from "path-type";
16
- import { promisify } from "node:util";
17
- import { brotliCompress, gzip } from "node:zlib";
18
- import prettyBytes from "pretty-bytes";
19
- import { toc } from "mdast-util-toc";
20
- import { read, write } from "to-vfile";
21
- import { VFile } from "vfile";
22
- import { Configuration } from "unified-engine";
23
- import untildify from "untildify";
24
- import { confirm, group, intro, note, outro, select } from "@clack/prompts";
25
- //#region src/lib/deep-merge-defined.ts
26
- function stripUndefinedDeep(object) {
27
- if (Array.isArray(object)) return object.map((v) => v !== null && typeof v === "object" ? stripUndefinedDeep(v) : v).filter((v) => v !== void 0);
28
- return Object.entries(object).map(([k, v]) => [k, v !== null && typeof v === "object" ? stripUndefinedDeep(v) : v]).reduce((acc, [k, v]) => v === void 0 ? acc : {
29
- ...acc,
30
- [k]: v
31
- }, {});
32
- }
33
- function deepMergeDefined(...objects) {
34
- const stripped = objects.map((v, i) => i === 0 ? v : stripUndefinedDeep(v));
35
- return deepmerge(...stripped);
36
- }
37
- //#endregion
38
- //#region src/lib/log.ts
39
- /**
40
- * The default logger instance for the library.
41
- */
42
- let log = createLogger({
43
- logToConsole: { showTime: false },
44
- name: "mdat"
45
- });
46
- setLogger$1(getChildLogger(log, "remark-mdat"));
47
- setLogger$2(getChildLogger(log, "metascope"));
48
- /**
49
- * Set the logger instance for the module. Export this for library consumers to
50
- * inject their own logger.
51
- *
52
- * @param logger - Accepts either a LogLayer instance or a Console- or
53
- * Stream-like log target
54
- */
55
- function setLogger(logger) {
56
- log = injectionHelper(logger);
57
- setLogger$1(getChildLogger(log, "remark-mdat"));
58
- setLogger$2(getChildLogger(log, "metascope"));
59
- }
60
- //#endregion
61
- //#region src/lib/mdat-json-loader.ts
62
- /**
63
- * Lets arbitrary JSON objects (like from package.json) become reasonably good
64
- * mdat rule sets HOWEVER cosmiconfig treats package.json as a special case and
65
- * will always load only specific keys from it So we have to intercept and load
66
- * them manually in config.ts
67
- */
68
- function mdatJsonLoader(filePath, content) {
69
- const defaultJsonLoader = defaultLoaders[".json"];
70
- return flattenJson(defaultJsonLoader(filePath, content));
71
- }
72
- function flattenJson(jsonObject, parentKey = "", result = {}) {
73
- for (const [key, value] of Object.entries(jsonObject)) {
74
- const fullPath = parentKey === "" ? key : `${parentKey}.${key}`;
75
- if (typeof value === "object" && value !== null && !Array.isArray(value)) flattenJson(value, fullPath, result);
76
- else if (value === null) result[fullPath] = "null";
77
- else result[fullPath] = value.toString();
78
- }
79
- return result;
80
- }
81
- //#endregion
82
- //#region src/lib/context.ts
83
- let metascopeMetadata;
84
- /**
85
- * Get a bunch of platform-agnostic local metadata via metascope, exposed
86
- * primarily for plugin developers. Result is memoized the result.
87
- *
88
- * @throws {Error} If no package.json is found
89
- */
90
- async function getContextMetadata() {
91
- if (metascopeMetadata !== void 0) return metascopeMetadata;
92
- metascopeMetadata = await getMetadata({
93
- absolute: false,
94
- offline: true,
95
- recursive: false,
96
- sources: [
97
- "arduinoLibraryProperties",
98
- "cinderCinderblockXml",
99
- "codemetaJson",
100
- "gitConfig",
101
- "githubActions",
102
- "gitStats",
103
- "goGoMod",
104
- "goGoreleaserYaml",
105
- "javaPomXml",
106
- "licenseFile",
107
- "metadataFile",
108
- "metascope",
109
- "nodePackageJson",
110
- "obsidianPluginManifestJson",
111
- "openframeworksAddonConfigMk",
112
- "openframeworksInstallXml",
113
- "processingLibraryProperties",
114
- "processingSketchProperties",
115
- "publiccodeYaml",
116
- "pythonPkgInfo",
117
- "pythonPyprojectToml",
118
- "pythonSetupCfg",
119
- "pythonSetupPy",
120
- "readmeFile",
121
- "rubyGemspec",
122
- "rustCargoToml",
123
- "xcodeInfoPlist",
124
- "xcodeProjectPbxproj"
125
- ]
126
- });
127
- return metascopeMetadata;
128
- }
129
- const GIT_PREFIX_REGEX = /^git\+/v;
130
- const GIT_SUFFIX_REGEX = /\.git$/v;
131
- const TRAILING_SLASH_REGEX = /\/$/v;
132
- const PACKAGE_MANAGER_REGEX = /^(?<name>[^@]+)@(?<version>[^+]+)/v;
133
- /**
134
- * Reset cached context metadata. Call between tests or when the underlying
135
- * project files may have changed on disk.
136
- *
137
- * @public
138
- */
139
- function resetContextMetadata() {
140
- metascopeMetadata = void 0;
141
- }
142
- const readmeMetadataTemplate = defineTemplate((context) => {
143
- const { githubActions, gitStats, licenseFile, metascope, nodePackageJson } = context;
144
- const codemeta = templates.codemetaJson(context, {});
145
- const nodePackage = helpers.firstOf(nodePackageJson)?.data;
146
- const licenseFileData = helpers.firstOf(licenseFile);
147
- const ciActionFilePath = helpers.ensureArray(githubActions).find((entry) => entry.data.name.toLowerCase() === "ci")?.source;
148
- const repoUrl = codemeta.codeRepository?.replace(GIT_PREFIX_REGEX, "").replace(GIT_SUFFIX_REGEX, "").replace(TRAILING_SLASH_REGEX, "");
149
- const bin = (() => {
150
- if (nodePackage === void 0) return;
151
- const binField = nodePackage.bin;
152
- if (binField === void 0) return;
153
- if (typeof binField === "string") return [nodePackage.name];
154
- const names = Object.keys(binField);
155
- return names.length > 0 ? names : void 0;
156
- })();
157
- const engines = (() => {
158
- const raw = nodePackage?.engines;
159
- if (raw === void 0) return;
160
- const entries = Object.entries(raw).filter((entry) => entry[1] !== void 0);
161
- return entries.length > 0 ? Object.fromEntries(entries) : void 0;
162
- })();
163
- const peerDependencies = (() => {
164
- if (nodePackage === void 0) return;
165
- const peers = nodePackage.peerDependencies;
166
- if (peers === void 0) return;
167
- const entries = Object.entries(peers).filter((entry) => entry[1] !== void 0);
168
- if (entries.length === 0) return;
169
- const meta = nodePackage.peerDependenciesMeta;
170
- return entries.map(([name, version]) => ({
171
- name,
172
- optional: meta?.[name]?.optional === true,
173
- version
174
- }));
175
- })();
176
- const developmentDependencies = (() => {
177
- if (nodePackage === void 0) return;
178
- const runtimes = helpers.ensureArray(nodePackage.devEngines?.runtime).map(({ name, version }) => ({
179
- name,
180
- version
181
- }));
182
- const packageManagers = helpers.ensureArray(nodePackage.devEngines?.packageManager).map(({ name, version }) => ({
183
- name,
184
- version
185
- }));
186
- const pinnedPackageManager = nodePackage.packageManager === void 0 ? void 0 : PACKAGE_MANAGER_REGEX.exec(nodePackage.packageManager)?.groups;
187
- if (pinnedPackageManager?.name !== void 0 && pinnedPackageManager.version !== void 0 && packageManagers.every((entry) => entry.name !== pinnedPackageManager.name)) packageManagers.push({
188
- name: pinnedPackageManager.name,
189
- version: pinnedPackageManager.version
190
- });
191
- if (runtimes.length === 0 && packageManagers.length === 0) return;
192
- return {
193
- packageManagers: packageManagers.length > 0 ? packageManagers : void 0,
194
- runtimes: runtimes.length > 0 ? runtimes : void 0
195
- };
196
- })();
197
- const firstAuthor = helpers.firstOf(helpers.ensureArray(codemeta.author));
198
- return {
199
- author: helpers.firstOf(helpers.mixedStringsToArray(helpers.toBasicNames(codemeta.author))),
200
- authorUrl: firstAuthor?.url,
201
- bin,
202
- ciActionFileName: ciActionFilePath === void 0 ? void 0 : path.basename(ciActionFilePath),
203
- description: codemeta.description,
204
- developmentDependencies,
205
- engines,
206
- isPublicNpmPackage: nodePackage?.private !== true && (nodePackage?.name.startsWith("@") && nodePackage.publishConfig?.access === "public" || true),
207
- issuesUrl: codemeta.issueTracker,
208
- license: helpers.toBasicLicense(helpers.firstOf(helpers.ensureArray(codemeta.license))),
209
- licenseFilePath: licenseFileData?.source,
210
- licenseUrl: licenseFileData?.data.match?.spdxUrl,
211
- name: codemeta.name,
212
- operatingSystem: codemeta.operatingSystem,
213
- peerDependencies,
214
- projectDirectory: metascope?.data.options.path === void 0 ? void 0 : `file://${metascope.data.options.path}`,
215
- repositoryUrl: repoUrl,
216
- runtimePlatform: codemeta.runtimePlatform,
217
- usesGitLfs: helpers.firstOf(gitStats)?.data.hasLfs === true,
218
- usesPnpm: helpers.usesPnpm(nodePackageJson)
219
- };
220
- });
221
- let readmeMetadata;
222
- /**
223
- * Nice data for readme rules
224
- *
225
- * @public
226
- */
227
- async function getReadmeMetadata() {
228
- if (readmeMetadata !== void 0) return readmeMetadata;
229
- const contextMetadata = await getContextMetadata();
230
- readmeMetadata = readmeMetadataTemplate(contextMetadata, {});
231
- return readmeMetadata;
232
- }
233
- /**
234
- * Reset cached readme metadata. Call between tests or when the underlying
235
- * project files may have changed on disk.
236
- *
237
- * @public
238
- */
239
- function resetReadmeMetadata() {
240
- readmeMetadata = void 0;
241
- }
242
- /**
243
- * Reset all cached metadata. Call between tests or when the underlying project
244
- * files may have changed on disk.
245
- */
246
- function resetMetadataCaches() {
247
- resetContextMetadata();
248
- resetReadmeMetadata();
249
- }
250
- //#endregion
251
- //#region src/lib/readme/rules/badges.ts
252
- var badges_default = { badges: { async content(options) {
253
- const validOptions = z.object({
254
- custom: z.record(z.string(), z.object({
255
- image: z.string(),
256
- link: z.string()
257
- })).optional(),
258
- npm: z.array(z.string()).optional()
259
- }).optional().parse(options);
260
- const metadata = await getReadmeMetadata();
261
- const { ciActionFileName, license, licenseUrl, name, repositoryUrl, usesGitLfs } = metadata;
262
- const badges = [];
263
- if (validOptions?.npm === void 0) {
264
- if (metadata.isPublicNpmPackage) badges.push(`[![NPM Package ${name}](https://img.shields.io/npm/v/${name}.svg)](https://www.npmjs.com/package/${name})`);
265
- } else for (const packageName of validOptions.npm) badges.push(`[![NPM Package ${packageName}](https://img.shields.io/npm/v/${packageName}.svg)](https://www.npmjs.com/package/${packageName})`);
266
- if (license !== void 0 && licenseUrl !== void 0) badges.push(`[![License: ${license}](https://img.shields.io/badge/License-${license.replaceAll("-", "--")}-yellow.svg)](${licenseUrl})`);
267
- if (ciActionFileName !== void 0 && repositoryUrl !== void 0) badges.push(`[![CI](${repositoryUrl}/actions/workflows/${ciActionFileName}/badge.svg)](${repositoryUrl}/actions/workflows/${ciActionFileName})`);
268
- if (usesGitLfs) badges.push("![Git LFS](https://img.shields.io/badge/Git%20LFS-enabled-F64935?logo=gitlfs&logoColor=white)");
269
- if (validOptions?.custom !== void 0) for (const [badgeName, { image, link }] of Object.entries(validOptions.custom)) badges.push(`[![${badgeName}](${image})](${link})`);
270
- return badges.join("\n");
271
- } } };
272
- //#endregion
273
- //#region src/lib/readme/rules/banner.ts
274
- var banner_default = { banner: { async content(options) {
275
- const validOptions = z.object({
276
- alt: z.string().optional(),
277
- src: z.string().optional()
278
- }).optional().parse(options);
279
- const src = validOptions?.src ?? await getBannerSrc();
280
- if (src === void 0) throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");
281
- if (!isUrl(src) && !await isFile(src)) throw new Error(`Banner image not found at "${src}"`);
282
- let alt = validOptions?.alt;
283
- if (alt === void 0) {
284
- const { name: packageName } = await getReadmeMetadata();
285
- if (packageName === void 0) throw new Error("Banner image alt text not available");
286
- alt = `${packageName} banner`;
287
- }
288
- return `![${alt}](${src})`;
289
- } } };
290
- async function getBannerSrc() {
291
- const { projectDirectory } = await getReadmeMetadata();
292
- if (projectDirectory === void 0) throw new Error("No project directory found");
293
- const [firstPath] = await globby([
294
- ".",
295
- "assets",
296
- "media",
297
- "readme-assets",
298
- "readme-media",
299
- "readme",
300
- "images",
301
- ".github/assets"
302
- ].map((location) => path.join(projectDirectory, location)), {
303
- deep: 1,
304
- expandDirectories: {
305
- extensions: [
306
- "png",
307
- "gif",
308
- "jpg",
309
- "jpeg",
310
- "svg",
311
- "webp"
312
- ],
313
- files: [
314
- "banner",
315
- "cover",
316
- "demo",
317
- "header",
318
- "hero",
319
- "image",
320
- "logo",
321
- "overview",
322
- "readme",
323
- "screenshot",
324
- "screenshots",
325
- "splash"
326
- ]
327
- }
328
- });
329
- return firstPath === void 0 ? void 0 : path.relative(process.cwd(), firstPath);
330
- }
331
- function isUrl(text, lenient = true) {
332
- if (typeof text !== "string") throw new TypeError("Expected a string");
333
- text = text.trim();
334
- if (text.includes(" ")) return false;
335
- if (URL.canParse(text)) return true;
336
- return lenient && URL.canParse(`https://${text}`);
337
- }
338
- //#endregion
339
- //#region src/lib/readme/rules/code.ts
340
- const LEADING_DOT_REGEX = /^\./v;
341
- var code_default = { code: { async content(options) {
342
- const validOptions = z.object({
343
- file: z.string(),
344
- language: z.string().optional(),
345
- trim: z.boolean().default(true)
346
- }).parse(options);
347
- const lang = (path.extname(validOptions.file) ?? "").replace(LEADING_DOT_REGEX, "");
348
- const exampleCode = await fs.readFile(path.join(process.cwd(), validOptions.file), "utf8");
349
- return `\`\`\`${lang}\n${validOptions.trim ? exampleCode.trim() : exampleCode}\n\`\`\``;
350
- } } };
351
- //#endregion
352
- //#region src/lib/readme/rules/contributing.ts
353
- var contributing_default = { contributing: { async content() {
354
- const { issuesUrl } = await getReadmeMetadata();
355
- if (issuesUrl === void 0) throw new Error("Could not find \"bugs.url\" entry in package.json");
356
- return [
357
- "## Contributing",
358
- "",
359
- `[Issues](${issuesUrl}) are welcome and appreciated.`,
360
- "",
361
- "Please open an issue to discuss changes before submitting a pull request. Unsolicited PRs (especially AI-generated ones) are unlikely to be merged.",
362
- "",
363
- "This repository uses [@kitschpatrol/shared-config](https://github.com/kitschpatrol/shared-config) (via its `ksc` CLI) for linting and formatting, plus [MDAT](https://github.com/kitschpatrol/mdat) for readme placeholder expansion."
364
- ].join("\n");
365
- } } };
366
- //#endregion
367
- //#region src/lib/readme/rules/dependencies.ts
368
- const PLATFORM_INFO = {
369
- bun: {
370
- display: "Bun",
371
- url: "https://bun.sh/"
372
- },
373
- deno: {
374
- display: "Deno",
375
- url: "https://deno.land/"
376
- },
377
- go: {
378
- display: "Go",
379
- url: "https://go.dev/"
380
- },
381
- java: {
382
- display: "Java",
383
- url: "https://www.java.com/"
384
- },
385
- node: {
386
- display: "Node.js",
387
- url: "https://nodejs.org/en"
388
- },
389
- python: {
390
- display: "Python",
391
- url: "https://www.python.org/"
392
- },
393
- ruby: {
394
- display: "Ruby",
395
- url: "https://www.ruby-lang.org/"
396
- },
397
- rust: {
398
- display: "Rust",
399
- url: "https://www.rust-lang.org/"
400
- }
401
- };
402
- var dependencies_default = { dependencies: { async content() {
403
- const { engines, operatingSystem, peerDependencies, runtimePlatform } = await getReadmeMetadata();
404
- const platformItems = [];
405
- if (engines !== void 0) for (const [name, version] of Object.entries(engines)) {
406
- const info = PLATFORM_INFO[name.toLowerCase()];
407
- const display = info ? `[${info.display}](${info.url})` : name;
408
- platformItems.push(`- ${display} ${version}`);
409
- }
410
- if (runtimePlatform !== void 0) for (const entry of runtimePlatform) {
411
- const spaceIndex = entry.indexOf(" ");
412
- const platformKey = spaceIndex > 0 ? entry.slice(0, spaceIndex) : entry;
413
- const version = spaceIndex > 0 ? entry.slice(spaceIndex + 1) : void 0;
414
- if (engines?.[platformKey] !== void 0) continue;
415
- const info = PLATFORM_INFO[platformKey.toLowerCase()];
416
- const display = info ? `[${info.display}](${info.url})` : platformKey;
417
- platformItems.push(version === void 0 || version === "" ? `- ${display}` : `- ${display} ${version}`);
418
- }
419
- if (operatingSystem !== void 0 && operatingSystem.length > 0) platformItems.push(`- Supported platforms: ${operatingSystem.join(", ")}`);
420
- const peerItems = [];
421
- if (peerDependencies !== void 0) for (const { name, optional, version } of peerDependencies) {
422
- const npmUrl = `https://www.npmjs.com/package/${name}`;
423
- const optionalSuffix = optional ? " _(optional)_" : "";
424
- peerItems.push(`- [${name}](${npmUrl}) ${version}${optionalSuffix}`);
425
- }
426
- const hasPlatform = platformItems.length > 0;
427
- const hasPeers = peerItems.length > 0;
428
- if (!hasPlatform && !hasPeers) return "";
429
- const sections = ["## Dependencies"];
430
- if (hasPlatform && hasPeers) sections.push("", "### Platform", "", ...platformItems, "", "### Peer Dependencies", "", ...peerItems);
431
- else if (hasPlatform) sections.push("", ...platformItems);
432
- else sections.push("", ...peerItems);
433
- return sections.join("\n");
434
- } } };
435
- //#endregion
436
- //#region src/lib/readme/rules/description.ts
437
- /**
438
- * Simple alias for short-description
439
- */
440
- var description_default = { description: { async content() {
441
- const { description } = await getReadmeMetadata();
442
- if (description === void 0) throw new Error("Could not find \"description\" entry in package.json");
443
- return `**${description}**`;
444
- } } };
445
- //#endregion
446
- //#region src/lib/readme/rules/development-dependencies.ts
447
- const TOOL_INFO = {
448
- bun: {
449
- display: "Bun",
450
- url: "https://bun.sh/"
451
- },
452
- deno: {
453
- display: "Deno",
454
- url: "https://deno.land/"
455
- },
456
- node: {
457
- display: "Node.js",
458
- url: "https://nodejs.org/en"
459
- },
460
- npm: {
461
- display: "npm",
462
- url: "https://www.npmjs.com/"
463
- },
464
- pnpm: {
465
- display: "pnpm",
466
- url: "https://pnpm.io/"
467
- },
468
- yarn: {
469
- display: "Yarn",
470
- url: "https://yarnpkg.com/"
471
- }
472
- };
473
- var development_dependencies_default = { "development-dependencies": { async content() {
474
- const { developmentDependencies } = await getReadmeMetadata();
475
- if (developmentDependencies === void 0) return "";
476
- const { packageManagers, runtimes } = developmentDependencies;
477
- const items = [];
478
- for (const { name, version } of [...runtimes ?? [], ...packageManagers ?? []]) {
479
- const info = TOOL_INFO[name.toLowerCase()];
480
- const display = info ? `[${info.display}](${info.url})` : name;
481
- items.push(version === void 0 || version === "" ? `- ${display}` : `- ${display} ${version}`);
482
- }
483
- return [
484
- "## Development Dependencies",
485
- "",
486
- ...items
487
- ].join("\n");
488
- } } };
489
- //#endregion
490
- //#region src/lib/readme/rules/dev-dependencies.ts
491
- /**
492
- * Simple alias for `development-dependencies`
493
- */
494
- var dev_dependencies_default = { "dev-dependencies": getSoleRule(development_dependencies_default) };
495
- //#endregion
496
- //#region src/lib/readme/rules/license.ts
497
- var license_default = { license: { async content() {
498
- const { author, authorUrl, license, licenseFilePath } = await getReadmeMetadata();
499
- if (author === void 0) throw new Error("Could not find author name in project");
500
- if (license === void 0 || licenseFilePath === void 0) throw new Error("Could not find license for project");
501
- return `## License\n[${license}](${licenseFilePath}) © ${authorUrl === void 0 ? author : `[${author}](${authorUrl})`}`;
502
- } } };
503
- //#endregion
504
- //#region src/lib/readme/rules/footer.ts
505
- var footer_default = { footer: { content: [getSoleRule(contributing_default), getSoleRule(license_default)] } };
506
- //#endregion
507
- //#region src/lib/readme/rules/short-description.ts
508
- /**
509
- * Simple alias for `description` rule, to match nomenclature in
510
- * [standard-readme](https://github.com/RichardLitt/standard-readme/blob/main/spec.md#short-description)
511
- * spec.
512
- */
513
- var short_description_default = { "short-description": getSoleRule(description_default) };
514
- //#endregion
515
- //#region src/lib/readme/rules/title.ts
516
- var title_default = { title: {
517
- async content(options) {
518
- const { postfix, prefix, titleCase } = z.object({
519
- postfix: z.string().optional().default(""),
520
- prefix: z.string().optional().default(""),
521
- titleCase: z.boolean().optional().default(false)
522
- }).parse(options ?? {});
523
- const { name: packageName } = await getReadmeMetadata();
524
- if (packageName === void 0) throw new Error("Could not find project name");
525
- return `# ${prefix}${titleCase ? makeTitleCase(packageName) : packageName}${postfix}`;
526
- },
527
- order: 2
528
- } };
529
- const SPLIT_FOR_TITLE_CASE_REGEX = /[ _\-]+/v;
530
- function makeTitleCase(text) {
531
- return text.split(SPLIT_FOR_TITLE_CASE_REGEX).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
532
- }
533
- //#endregion
534
- //#region src/lib/readme/rules/header.ts
535
- var header_default = { header: {
536
- content: [
537
- getSoleRule(title_default),
538
- getSoleRule(banner_default),
539
- getSoleRule(badges_default),
540
- getSoleRule(short_description_default)
541
- ],
542
- order: 2
543
- } };
544
- //#endregion
545
- //#region src/lib/readme/rules/install.ts
546
- var install_default = { install: { async content() {
547
- const { bin, engines, isPublicNpmPackage, name, runtimePlatform, usesPnpm } = await getReadmeMetadata();
548
- if (name === void 0) throw new Error("Could not find project name");
549
- const lines = ["## Install"];
550
- if (isPublicNpmPackage || engines?.node !== void 0 || runtimePlatform?.includes("node")) {
551
- const pmAdd = usesPnpm ? "pnpm add" : "npm install";
552
- const pmx = usesPnpm ? "pnpx" : "npx";
553
- lines.push("", "```sh", `${pmAdd} ${name}`, "```");
554
- if (bin !== void 0 && bin.length > 0) lines.push("", "Or run it directly:", "", "```sh", `${pmx} ${name}`, "```");
555
- } else if (runtimePlatform?.some((p) => p.startsWith("python"))) lines.push("", "```sh", `pip install ${name}`, "```");
556
- else if (runtimePlatform?.some((p) => p.startsWith("rust"))) lines.push("", "```sh", `cargo install ${name}`, "```");
557
- else if (runtimePlatform?.some((p) => p.startsWith("go"))) lines.push("", "```sh", `go install ${name}@latest`, "```");
558
- else if (runtimePlatform?.some((p) => p.startsWith("ruby"))) lines.push("", "```sh", `gem install ${name}`, "```");
559
- else throw new Error("Could not determine project ecosystem for install instructions");
560
- return lines.join("\n");
561
- } } };
562
- //#endregion
563
- //#region src/lib/readme/rules/utilities/size/size-report.ts
564
- const brotliCompressAsync = promisify(brotliCompress);
565
- const gzipCompressAsync = promisify(gzip);
566
- /**
567
- * Creates a SizeInfo object with formatted values
568
- *
569
- * @param bytes - Size in bytes
570
- * @param originalSize - Original file size for percentage calculation
571
- */
572
- function createSizeInfo(bytes, originalSize, precision) {
573
- const percent = originalSize === 0 ? 0 : (originalSize - bytes) / originalSize * 100;
574
- return {
575
- bytes,
576
- bytesPretty: prettyBytes(bytes, { maximumFractionDigits: precision }),
577
- percent,
578
- percentPretty: `${Math.round(percent)}%`
579
- };
580
- }
581
- /**
582
- * Analyzes a file's size and its compressed sizes using Brotli and Gzip
583
- *
584
- * @param filePath - Path to the file to analyze
585
- * @param precision - Maximum number of decimal places in formatted byte sizes
586
- *
587
- * @returns Promise containing detailed size report
588
- * @throws {Error} If file cannot be read or compressed
589
- */
590
- async function createSizeReport(filePath, precision = 1) {
591
- try {
592
- const fileContent = await fs.readFile(filePath);
593
- const originalSize = fileContent.length;
594
- const [brotliCompressed, gzipCompressed] = await Promise.all([brotliCompressAsync(fileContent), gzipCompressAsync(fileContent)]);
595
- return {
596
- brotli: createSizeInfo(brotliCompressed.length, originalSize, precision),
597
- gzip: createSizeInfo(gzipCompressed.length, originalSize, precision),
598
- original: createSizeInfo(originalSize, originalSize, precision)
599
- };
600
- } catch (error) {
601
- throw new Error(`Failed to analyze file: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
602
- }
603
- }
604
- //#endregion
605
- //#region src/lib/readme/rules/size.ts
606
- const optionsSchema$1 = z.object({
607
- compression: z.enum([
608
- "none",
609
- "brotli",
610
- "gzip"
611
- ]).optional().default("none"),
612
- file: z.string()
613
- });
614
- function getSizeForCompression(report, compression) {
615
- switch (compression) {
616
- case "brotli": return report.brotli.bytesPretty;
617
- case "gzip": return report.gzip.bytesPretty;
618
- case "none": return report.original.bytesPretty;
619
- }
620
- }
621
- var size_default = { size: { async content(options) {
622
- const validOptions = optionsSchema$1.parse(options);
623
- return getSizeForCompression(await createSizeReport(path.join(process.cwd(), validOptions.file)), validOptions.compression);
624
- } } };
625
- //#endregion
626
- //#region src/lib/readme/rules/size-table.ts
627
- const fileSchema = z.union([z.string(), z.array(z.string())]).transform((files) => Array.isArray(files) ? files : [files]);
628
- const optionsSchema = z.union([z.object({
629
- brotli: z.boolean().optional().default(true),
630
- file: fileSchema,
631
- gzip: z.boolean().optional().default(true),
632
- original: z.boolean().optional().default(true),
633
- precision: z.number().int().min(0).max(100).optional().default(0),
634
- showPercentage: z.boolean().optional().default(false)
635
- }), z.object({
636
- brotli: z.boolean().optional().default(true),
637
- files: fileSchema,
638
- gzip: z.boolean().optional().default(true),
639
- original: z.boolean().optional().default(true),
640
- precision: z.number().int().min(0).max(100).optional().default(0),
641
- showPercentage: z.boolean().optional().default(false)
642
- })]).transform((options) => {
643
- if ("file" in options) {
644
- const { file, ...rest } = options;
645
- return {
646
- files: file,
647
- ...rest
648
- };
649
- }
650
- return options;
651
- });
652
- function formatMarkdownTable(reports, options) {
653
- const headers = ["File"];
654
- if (options.original) headers.push("Original");
655
- if (options.gzip) headers.push("Gzip");
656
- if (options.brotli) headers.push("Brotli");
657
- const separators = headers.map(() => "---");
658
- const rows = reports.map(([file, report]) => {
659
- const row = [path.basename(file)];
660
- if (options.original) row.push(report.original.bytesPretty);
661
- if (options.gzip) row.push(options.showPercentage ? `${report.gzip.bytesPretty} (${report.gzip.percentPretty})` : report.gzip.bytesPretty);
662
- if (options.brotli) row.push(options.showPercentage ? `${report.brotli.bytesPretty} (${report.brotli.percentPretty})` : report.brotli.bytesPretty);
663
- return row;
664
- });
665
- return [
666
- `| ${headers.join(" | ")} |`,
667
- `| ${separators.join(" | ")} |`,
668
- ...rows.map((row) => `| ${row.join(" | ")} |`)
669
- ].join("\n");
670
- }
671
- var size_table_default = { "size-table": { async content(options) {
672
- const validOptions = optionsSchema.parse(options);
673
- return formatMarkdownTable(await Promise.all(validOptions.files.map(async (file) => {
674
- return [file, await createSizeReport(path.join(process.cwd(), file), validOptions.precision)];
675
- })), {
676
- brotli: validOptions.brotli,
677
- gzip: validOptions.gzip,
678
- original: validOptions.original,
679
- showPercentage: validOptions.showPercentage
680
- });
681
- } } };
682
- //#endregion
683
- //#region src/lib/readme/rules/table-of-contents.ts
684
- var table_of_contents_default = { "table-of-contents": {
685
- async content(options, { tree }) {
686
- const validOptions = z.object({ depth: z.union([
687
- z.literal(1),
688
- z.literal(2),
689
- z.literal(3),
690
- z.literal(4),
691
- z.literal(5),
692
- z.literal(6)
693
- ]).optional() }).optional().parse(options);
694
- const result = toc(tree, {
695
- heading: null,
696
- maxDepth: validOptions?.depth ?? 3,
697
- tight: true
698
- });
699
- if (result.map === void 0) throw new Error("Could not generate table of contents");
700
- const heading = `## Table of contents`;
701
- const rootWrapper = {
702
- children: result.map.children,
703
- type: "root"
704
- };
705
- return [heading, remark().use(remarkGfm).stringify(rootWrapper).replaceAll("\n\n", "\n")].join("\n");
706
- },
707
- order: 1
708
- } };
709
- //#endregion
710
- //#region src/lib/readme/rules/toc.ts
711
- /**
712
- * Simple alias for table-of-contents
713
- */
714
- var toc_default = { toc: getSoleRule(table_of_contents_default) };
715
- //#endregion
716
- //#region src/lib/readme/rules/index.ts
717
- var rules_default = {
718
- ...badges_default,
719
- ...banner_default,
720
- ...code_default,
721
- ...contributing_default,
722
- ...dependencies_default,
723
- ...description_default,
724
- ...dev_dependencies_default,
725
- ...development_dependencies_default,
726
- ...footer_default,
727
- ...header_default,
728
- ...install_default,
729
- ...license_default,
730
- ...short_description_default,
731
- ...size_default,
732
- ...size_table_default,
733
- ...table_of_contents_default,
734
- ...title_default,
735
- ...toc_default
736
- };
737
- //#endregion
738
- //#region src/lib/config.ts
739
- let _configExplorer;
740
- let _additionalConfigExplorer;
741
- function getConfigExplorer() {
742
- _configExplorer ??= cosmiconfig("mdat", { loaders: { ".ts": TypeScriptLoader() } });
743
- return _configExplorer;
744
- }
745
- function getAdditionalConfigExplorer() {
746
- _additionalConfigExplorer ??= cosmiconfig("mdat", { loaders: {
747
- ".json": mdatJsonLoader,
748
- ".ts": TypeScriptLoader()
749
- } });
750
- return _additionalConfigExplorer;
751
- }
752
- /**
753
- * Load and validate mdat configuration. Uses cosmiconfig to search in the usual
754
- * places. Merge precedence: Base Defaults < Defaults < Searched Config <
755
- * Additional Config
756
- */
757
- async function loadConfig(options) {
758
- const { additionalConfig, defaults = rules_default, searchFrom } = options ?? {};
759
- let finalConfig = { mdat: `Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat).` };
760
- finalConfig = deepMergeDefined(finalConfig, defaults);
761
- const results = await getConfigExplorer().search(searchFrom);
762
- if (results) {
763
- const { config, filepath } = results;
764
- let possibleRules = config;
765
- log.debug(`Using config from "${filepath}"`);
766
- if (typeof config === "string" && filepath.endsWith("package.json")) {
767
- log.debug(`Detected shared config string: "${config}"`);
768
- const { default: sharedConfig } = await import(config);
769
- possibleRules = sharedConfig;
770
- }
771
- const validated = validateConfig(possibleRules);
772
- if (validated) finalConfig = deepMergeDefined(finalConfig, validated);
773
- }
774
- if (additionalConfig !== void 0) {
775
- const additionalConfigArray = Array.isArray(additionalConfig) ? additionalConfig : [additionalConfig];
776
- for (const configOrPath of additionalConfigArray) {
777
- let loaded;
778
- if (typeof configOrPath === "string") {
779
- let loadResults;
780
- if (path.basename(configOrPath).endsWith("package.json")) loadResults = {
781
- config: mdatJsonLoader(configOrPath, await fs.readFile(configOrPath, "utf8")),
782
- filepath: configOrPath
783
- };
784
- else loadResults = await getAdditionalConfigExplorer().load(configOrPath);
785
- if (loadResults === null || loadResults === void 0) continue;
786
- const { config: loadedConfig, filepath } = loadResults;
787
- log.debug(`Loaded additional config from "${filepath}"`);
788
- loaded = loadedConfig;
789
- } else loaded = configOrPath;
790
- if (loaded === void 0) continue;
791
- log.debug("Merging config");
792
- const validated = validateConfig(loaded);
793
- if (validated) finalConfig = deepMergeDefined(finalConfig, validated);
794
- }
795
- }
796
- const prettyRules = Object.keys(finalConfig).toSorted().map((rule) => `"${picocolors.green(picocolors.bold(rule))}"`);
797
- log.debug(`Loaded ${picocolors.bold(prettyRules.length)} mdat comment expansion ${plur("rule", prettyRules.length)}:`);
798
- for (const rule of prettyRules) log.debug(`\t${rule}`);
799
- return finalConfig;
800
- }
801
- function validateConfig(value) {
802
- if (rulesSchema.safeParse(value).success) return value;
803
- log.warn(`Config has the wrong shape. Ignoring and using default configuration:\n${JSON.stringify(value, void 0, 2)}`);
804
- }
805
- /**
806
- * Convenience function for merging configs. Rightmost config takes precedence.
807
- */
808
- function mergeConfig(a, b) {
809
- return deepMergeDefined(a, b);
810
- }
811
- /**
812
- * Identity function providing type inference for mdat configuration files.
813
- */
814
- function defineConfig(config) {
815
- return config;
816
- }
817
- //#endregion
818
- //#region src/lib/format.ts
819
- let cachedPrettier;
820
- const configCache = /* @__PURE__ */ new Map();
821
- /**
822
- * Format a markdown string with Prettier, using config discovered from the file
823
- * path. Requires `prettier` to be installed as a peer dependency.
824
- */
825
- async function formatWithPrettier(content, filePath) {
826
- if (cachedPrettier === void 0) try {
827
- cachedPrettier = await import("prettier");
828
- } catch {
829
- throw new Error("The --format flag requires `prettier` to be installed. Run: pnpm add -D prettier");
830
- }
831
- const configKey = filePath === void 0 || filePath === "" ? process.cwd() : path.dirname(filePath);
832
- let config = configCache.get(configKey);
833
- if (config === void 0 && !configCache.has(configKey)) {
834
- config = await cachedPrettier.resolveConfig(filePath ?? process.cwd());
835
- configCache.set(configKey, config);
836
- if (config) log.debug(`Resolved Prettier config for "${configKey}"`);
837
- }
838
- return cachedPrettier.format(content, {
839
- ...config,
840
- filepath: filePath,
841
- parser: "markdown"
842
- });
843
- }
844
- //#endregion
845
- //#region src/lib/utilities.ts
846
- function zeroPad(n, nMax) {
847
- const places = nMax === 0 ? 1 : Math.floor(Math.log10(Math.abs(nMax)) + 1);
848
- return n.toString().padStart(places, "0");
849
- }
850
- async function getInputOutputPaths(inputs, output, name, extension) {
851
- const paths = [];
852
- for (const [index, file] of inputs.entries()) {
853
- const inputOutputPath = await getInputOutputPath(file, output, name, extension, name !== void 0 && name !== "" && inputs.length > 1 ? `-${zeroPad(index + 1, inputs.length)}` : "");
854
- paths.push(inputOutputPath);
855
- }
856
- return paths;
857
- }
858
- async function getInputOutputPath(input, output, name, extension, nameSuffix = "") {
859
- const resolvedInput = expandPath(input);
860
- if (!isFileSync(resolvedInput)) throw new Error(`Input file not found: "${resolvedInput}"`);
861
- const resolvedOutput = output === void 0 || output === "" ? void 0 : expandPath(output);
862
- if (resolvedOutput !== void 0) {
863
- if (isFileSync(resolvedOutput)) throw new Error(`Output path must be a directory, received a file path: "${resolvedOutput}"`);
864
- await fs.mkdir(resolvedOutput, { recursive: true });
865
- }
866
- return {
867
- input: resolvedInput,
868
- name: `${name === void 0 || name === "" ? path.basename(resolvedInput, path.extname(resolvedInput)) : path.basename(name, path.extname(name))}${nameSuffix}${extension === void 0 ? name !== void 0 && path.extname(name) !== "" ? path.extname(name) : path.extname(input) : `.${extension}`}`,
869
- output: resolvedOutput ?? path.dirname(resolvedInput)
870
- };
871
- }
872
- function expandPath(file) {
873
- return untildify(file);
874
- }
875
- function ensureArray(value) {
876
- if (value === void 0 || value === null) return [];
877
- return Array.isArray(value) ? value : [value];
878
- }
879
- const README_SEARCH_REGEX = /^readme(?:\.\w+)?$/iv;
880
- /**
881
- * Finds a readme file in the current working directory (case-insensitive).
882
- */
883
- async function findReadme() {
884
- log.debug("Searching for readme in current directory...");
885
- const readme = (await fs.readdir(process.cwd())).find((entry) => README_SEARCH_REGEX.test(entry));
886
- if (readme !== void 0) {
887
- const absolutePath = path.resolve(readme);
888
- log.debug(`Found readme at "${absolutePath}"`);
889
- return absolutePath;
890
- }
891
- }
892
- /**
893
- * Searches up for a readme.md file.
894
- *
895
- * @throws {Error} If no readme is found
896
- */
897
- async function findReadmeThrows() {
898
- const readme = await findReadme();
899
- if (readme === void 0) throw new Error("No readme found");
900
- return readme;
901
- }
902
- let cachedAmbientRemarkConfig;
903
- async function loadAmbientRemarkConfig() {
904
- if (cachedAmbientRemarkConfig !== void 0) return cachedAmbientRemarkConfig;
905
- const ambientConfig = new Configuration({
906
- cwd: process.cwd(),
907
- detectConfig: true,
908
- packageField: "remarkConfig",
909
- rcName: ".remarkrc"
910
- });
911
- const configResult = await new Promise((resolve) => {
912
- ambientConfig.load("", (error, result) => {
913
- if (error) {
914
- log.error(String(error));
915
- resolve(void 0);
916
- return;
917
- }
918
- resolve(result);
919
- });
920
- });
921
- if (configResult) {
922
- const { filePath } = configResult;
923
- if (filePath === void 0) log.debug("No ambient Remark configuration file found");
924
- else log.debug(`Found and loaded ambient Remark configuration from "${filePath}"`);
925
- cachedAmbientRemarkConfig = stripLintPlugins(configResult);
926
- return cachedAmbientRemarkConfig;
927
- }
928
- log.debug("No ambient Remark configuration found");
929
- cachedAmbientRemarkConfig = {
930
- filePath: void 0,
931
- plugins: [],
932
- settings: {}
933
- };
934
- return cachedAmbientRemarkConfig;
935
- }
936
- /**
937
- * Strip remark-lint plugins from an ambient config. Lint plugins only produce
938
- * VFile warnings and never modify the AST or output — running them during
939
- * expansion is pure overhead.
940
- */
941
- function stripLintPlugins(config) {
942
- return {
943
- ...config,
944
- plugins: config.plugins.filter((entry) => {
945
- const plugin = Array.isArray(entry) ? entry[0] : entry;
946
- if (typeof plugin !== "function") return true;
947
- const { name } = plugin;
948
- return name !== "remarkLint" && !name.startsWith("remark-lint:") && name !== "remarkValidateLinks";
949
- })
950
- };
951
- }
952
- //#endregion
953
- //#region src/lib/processors.ts
954
- async function processFiles(files, loader, processorGetter, name, output, config) {
955
- const [resolvedConfig, localRemarkConfig] = await Promise.all([loader({ additionalConfig: config }), loadAmbientRemarkConfig()]);
956
- const inputOutputPaths = await getInputOutputPaths(ensureArray(files), output, name, "md");
957
- const resolvedProcessor = processorGetter(resolvedConfig, localRemarkConfig);
958
- return await Promise.all(inputOutputPaths.map(async ({ input, name: outputName, output: outputDirectory }) => {
959
- const inputFile = await read(input);
960
- const result = await resolvedProcessor.process(inputFile);
961
- result.dirname = outputDirectory;
962
- result.basename = outputName;
963
- return result;
964
- }));
965
- }
966
- async function processString(markdown, loader, processorGetter, config) {
967
- const [resolvedConfig, localRemarkConfig] = await Promise.all([loader({ additionalConfig: config }), loadAmbientRemarkConfig()]);
968
- return processorGetter(resolvedConfig, localRemarkConfig).process(new VFile(markdown));
969
- }
970
- function getExpandProcessor(config, ambientRemarkConfig) {
971
- return remark().use({ settings: {
972
- bullet: "-",
973
- emphasis: "_"
974
- } }).use(remarkGfm).use(ambientRemarkConfig).use(() => async function(tree, file) {
975
- mdatSplit(tree, file);
976
- mdatCollapse(tree, file);
977
- await mdatExpand(tree, file, config);
978
- });
979
- }
980
- function getCollapseProcessor(_config, ambientRemarkConfig) {
981
- return remark().use({ settings: {
982
- bullet: "-",
983
- emphasis: "_"
984
- } }).use(remarkGfm).use(ambientRemarkConfig).use(() => function(tree, file) {
985
- mdatSplit(tree, file);
986
- mdatCollapse(tree, file);
987
- });
988
- }
989
- function getStripProcessor(_config, ambientRemarkConfig) {
990
- return remark().use({ settings: {
991
- bullet: "-",
992
- emphasis: "_"
993
- } }).use(remarkGfm).use(ambientRemarkConfig).use(() => function(tree, file) {
994
- mdatSplit(tree, file);
995
- mdatStrip(tree, file);
996
- });
997
- }
998
- //#endregion
999
- //#region src/lib/readme/templates/index.ts
1000
- var templates_default = {
1001
- "MDAT Readme": {
1002
- content: {
1003
- compound: "<!-- header -->\n\n<!-- table-of-contents -->\n\n## Overview\n\n## Getting started\n\n### Dependencies\n\n### Installation\n\n## Usage\n\n### Library\n\n#### API\n\n#### Examples\n\n### CLI\n\n#### Commands\n\n#### Examples\n\n## Background\n\n### Motivation\n\n### Implementation notes\n\n### Similar projects\n\n## The future\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Acknowledgments\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- footer -->\n",
1004
- explicit: "<!-- title -->\n\n<!-- banner -->\n\n<!-- badges -->\n\n<!-- short-description -->\n\n<!-- table-of-contents -->\n\n## Overview\n\n## Getting started\n\n### Dependencies\n\n### Installation\n\n## Usage\n\n### Library\n\n#### API\n\n#### Examples\n\n### CLI\n\n#### Commands\n\n#### Examples\n\n## Background\n\n### Motivation\n\n### Implementation notes\n\n### Similar projects\n\n## The future\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Acknowledgments\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- contributing -->\n\n<!-- license -->\n"
1005
- },
1006
- description: "The house style. An expansive starting point. Prune to your context and taste.",
1007
- exampleLink: "https://github.com/kitschpatrol/mdat/blob/main/readme.md"
1008
- },
1009
- "Standard Readme Basic": {
1010
- content: {
1011
- compound: "<!-- header -->\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" }) --> comment as well.\n```\n\n<!-- footer -->\n",
1012
- explicit: "<!-- title -->\n\n<!-- short-description -->\n\n<!-- table-of-contents -->\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" })--> comment as well.\n```\n\n<!-- contributing -->\n\n<!-- license -->\n"
1013
- },
1014
- description: "Includes only the \"required\" sections from the Standard Readme specification.",
1015
- exampleLink: "https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/minimal-readme.md"
1016
- },
1017
- "Standard Readme Full": {
1018
- content: {
1019
- compound: "<!-- header -->\n\n_Long description goes here._\n\n_No heading. Cover the main reasons for building the repository. This should describe your module in broad terms, generally in just a few paragraphs; more detail of the module's routines or methods, lengthy code examples, or other in-depth material should be given in subsequent sections._\n\n<!-- table-of-contents -->\n\n## Background\n\n_Cover motivation. Cover abstract dependencies. Cover intellectual provenance: A See Also section is also fitting._\n\n### See also\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n### Dependencies\n\n_Required if there are unusual dependencies or dependencies that must be manually installed._\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" })--> comment as well.\n```\n\n```ts\n// If importable, code block indicating both import functionality and usage.\n```\n\n### CLI\n\n```ts\n// If CLI compatible, code block indicating common usage.\n```\n\n## _Extra Sections (Rename)_\n\n## Security\n\n## API\n\n_Describe exported functions and objects._\n\n- _Describe signatures, return types, callbacks, and events._\n- _Cover types covered where not obvious._\n- _Describe caveats._\n- _If using an external API generator (like go-doc, js-doc, or so on), point to an external API.md file. This can be the only item in the section, if present._\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Thanks\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- footer -->\n",
1020
- explicit: "<!-- title -->\n\n<!-- banner -->\n\n<!-- badges -->\n\n<!-- short-description -->\n\n_Long description goes here._\n\n_No heading. Cover the main reasons for building the repository. This should describe your module in broad terms, generally in just a few paragraphs; more detail of the module's routines or methods, lengthy code examples, or other in-depth material should be given in subsequent sections._\n\n<!-- table-of-contents -->\n\n## Background\n\n_Cover motivation. Cover abstract dependencies. Cover intellectual provenance: A See Also section is also fitting._\n\n### See also\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n### Dependencies\n\n_Required if there are unusual dependencies or dependencies that must be manually installed._\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" })--> comment as well.\n```\n\n```ts\n// If importable, code block indicating both import functionality and usage.\n```\n\n### CLI\n\n```ts\n// If CLI compatible, code block indicating common usage.\n```\n\n## _Extra Sections (Rename)_\n\n## Security\n\n## API\n\n_Describe exported functions and objects._\n\n- _Describe signatures, return types, callbacks, and events._\n- _Cover types covered where not obvious._\n- _Describe caveats._\n- _If using an external API generator (like go-doc, js-doc, or so on), point to an external API.md file. This can be the only item in the section, if present._\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Thanks\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- contributing -->\n\n<!-- license -->\n"
1021
- },
1022
- description: "Includes all sections from the Standard Readme specification.",
1023
- exampleLink: "https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/maximal-readme.md"
1024
- }
1025
- };
1026
- //#endregion
1027
- //#region src/lib/readme/create.ts
1028
- /**
1029
- * Creates a new readme file interactively.
1030
- *
1031
- * @returns Path to the created readme file.
1032
- */
1033
- async function createReadmeInteractive() {
1034
- const readmePath = await findReadme();
1035
- intro(`Running ${picocolors.bold("mdat create")} interactively`);
1036
- const newReadmePath = await createReadme(await group({
1037
- async overwrite() {
1038
- if (readmePath === void 0) return true;
1039
- if (await confirm({
1040
- message: `Found an existing readme at "${picocolors.blue(readmePath)}". Do you want to overwrite it?`,
1041
- active: "Overwrite",
1042
- inactive: "Exit"
1043
- }) === false) throw new Error("`mdat create` was cancelled to avoid an overwrite - no changes were made");
1044
- return true;
1045
- },
1046
- template: async () => select({
1047
- message: "Which template would you like to use?",
1048
- options: getTemplateOptions()
1049
- }),
1050
- compound: async () => select({
1051
- message: "Do you want to use \"compound comments\" where possible, which combine several expansions into a single comment block?",
1052
- options: [{
1053
- label: `Yes: Combine things like ${picocolors.green("<!-- title -->")} and ${picocolors.green("<!-- badges -->")} in a single ${picocolors.green("<!-- header -->")} comment.`,
1054
- value: true
1055
- }, {
1056
- label: "No: Use individual MDAT expansion comments for each section.",
1057
- value: false
1058
- }]
1059
- }),
1060
- expand: async () => confirm({
1061
- initialValue: true,
1062
- message: "Do you want to run `mdat expand` now to expand the template with content from your project metadata?"
1063
- })
1064
- }, { onCancel() {
1065
- throw new Error("`mdat create` was cancelled - no changes were made");
1066
- } }));
1067
- note(`Readme created: "${picocolors.blue(picocolors.bold(newReadmePath))}"`);
1068
- outro("Done!");
1069
- return newReadmePath;
1070
- }
1071
- /**
1072
- * Creates a new readme file with the given options.
1073
- *
1074
- * @returns Path to the created readme file.
1075
- */
1076
- async function createReadme(options) {
1077
- const resolvedOptions = deepMergeDefined({
1078
- compound: true,
1079
- output: process.cwd(),
1080
- overwrite: true,
1081
- expand: true,
1082
- template: Object.keys(templates_default)[0]
1083
- }, options ?? {});
1084
- const templateString = getTemplateForConfig(resolvedOptions.template, resolvedOptions.compound);
1085
- const readmePath = path.join(resolvedOptions.output, "readme.md");
1086
- if (!resolvedOptions.overwrite) {
1087
- let exists = true;
1088
- try {
1089
- await fs.access(readmePath);
1090
- } catch {
1091
- exists = false;
1092
- }
1093
- if (exists) throw new Error(`Readme already exists at "${readmePath}". Use the overwrite option to replace it.`);
1094
- }
1095
- await fs.writeFile(readmePath, templateString, "utf8");
1096
- if (resolvedOptions.expand) {
1097
- const [result] = await expand(readmePath);
1098
- if (result === void 0) throw new Error(`Failed to expand readme at "${readmePath}"`);
1099
- await write(result);
1100
- }
1101
- return readmePath;
1102
- }
1103
- function getTemplateForConfig(templateKey, compound) {
1104
- if (!Object.hasOwn(templates_default, templateKey)) throw new Error(`Unknown template "${templateKey}". Available templates: ${Object.keys(templates_default).join(", ")}`);
1105
- return templates_default[templateKey].content[compound ? "compound" : "explicit"];
1106
- }
1107
- function getTemplateOptions() {
1108
- return Object.entries(templates_default).map(([key, value]) => ({
1109
- label: key,
1110
- hint: value.description,
1111
- value: key
1112
- }));
1113
- }
1114
- //#endregion
1115
- //#region src/lib/api.ts
1116
- /**
1117
- * Expand MDAT comments in one or more Markdown files. If no files are provided,
1118
- * auto-finds the closest readme.md. Writing is the responsibility of the caller
1119
- * (e.g. via `await write(result)`)
1120
- *
1121
- * @returns An array of VFiles
1122
- */
1123
- async function expand(files, name, output, config, options) {
1124
- files ??= await findReadmeThrows();
1125
- const results = await processFiles(files, loadConfig, getExpandProcessor, name, output, config);
1126
- if (options?.format) await formatResults(results);
1127
- return results;
1128
- }
1129
- /**
1130
- * Expand MDAT comments in a Markdown string.
1131
- */
1132
- async function expandString(markdown, config, options) {
1133
- const result = await processString(markdown, loadConfig, getExpandProcessor, config);
1134
- if (options?.format) await formatResults([result]);
1135
- return result;
1136
- }
1137
- /**
1138
- * Collapse MDAT comments in one or more Markdown files. If no files are
1139
- * provided, auto-finds the closest readme.md. Writing is the responsibility of
1140
- * the caller (e.g. via `await write(result)`)
1141
- *
1142
- * @returns An array of VFiles
1143
- */
1144
- async function collapse(files, name, output, config, options) {
1145
- files ??= await findReadmeThrows();
1146
- const results = await processFiles(files, loadConfig, getCollapseProcessor, name, output, config);
1147
- if (options?.format) await formatResults(results);
1148
- return results;
1149
- }
1150
- /**
1151
- * Collapse MDAT comments in a Markdown string.
1152
- */
1153
- async function collapseString(markdown, config, options) {
1154
- const result = await processString(markdown, loadConfig, getCollapseProcessor, config);
1155
- if (options?.format) await formatResults([result]);
1156
- return result;
1157
- }
1158
- /**
1159
- * Strips MDAT comments in one or more Markdown files without touching other
1160
- * content. Does _not_ automatically expand Mdat content before stripping the
1161
- * tags. If no files are provided, auto-finds the closest readme.md. Writing is
1162
- * the responsibility of the caller (e.g. via `await write(result)`)
1163
- *
1164
- * @returns An array of VFiles
1165
- */
1166
- async function strip(files, name, output, config, options) {
1167
- files ??= await findReadmeThrows();
1168
- const results = await processFiles(files, loadConfig, getStripProcessor, name, output, config);
1169
- if (options?.format) await formatResults(results);
1170
- return results;
1171
- }
1172
- /**
1173
- * Strip MDAT comments from a Markdown string.
1174
- */
1175
- async function stripString(markdown, config, options) {
1176
- const result = await processString(markdown, loadConfig, getStripProcessor, config);
1177
- if (options?.format) await formatResults([result]);
1178
- return result;
1179
- }
1180
- /**
1181
- * Dry-run expand and compare with file on disk. If no files are provided,
1182
- * auto-finds the closest readme.md.
1183
- *
1184
- * @returns Per-file sync status and expanded VFiles
1185
- */
1186
- async function check(files, config, options) {
1187
- files ??= await findReadmeThrows();
1188
- const { read } = await import("to-vfile");
1189
- const resolvedFiles = Array.isArray(files) ? files : [files];
1190
- const [originals, results] = await Promise.all([Promise.all(resolvedFiles.map(async (f) => read(f))), processFiles(files, loadConfig, getExpandProcessor, void 0, void 0, config)]);
1191
- if (options?.format) await formatResults(results);
1192
- return results.map((result, i) => {
1193
- const original = originals[i];
1194
- if (original === void 0) throw new Error(`Missing original file for comparison at index ${i}`);
1195
- return compareWithDiff(original, result, options);
1196
- });
1197
- }
1198
- /**
1199
- * Check if MDAT comments in a Markdown string are up to date by expanding and
1200
- * comparing per-tag.
1201
- */
1202
- async function checkString(markdown, config, options) {
1203
- const { VFile: VF } = await import("vfile");
1204
- const original = new VF(markdown);
1205
- const result = await processString(markdown, loadConfig, getExpandProcessor, config);
1206
- if (options?.format) await formatResults([result]);
1207
- return compareWithDiff(original, result, options);
1208
- }
1209
- function compareWithDiff(original, result, options) {
1210
- const inSync = original.toString().replaceAll("\r\n", "\n") === result.toString();
1211
- if (!inSync) {
1212
- const parser = remark().use(remarkGfm);
1213
- const originalTree = parser.parse(original.toString());
1214
- mdatSplit(originalTree, original);
1215
- const expandedTree = parser.parse(result.toString());
1216
- mdatSplit(expandedTree, result);
1217
- const diffResults = mdatDiff(originalTree, original, expandedTree, result);
1218
- if (options?.format && diffResults.every((r) => r.status === "ok")) {
1219
- const message = result.message("Formatting differences outside mdat tags", { source: "diff" });
1220
- message.fatal = false;
1221
- }
1222
- }
1223
- return {
1224
- inSync,
1225
- result
1226
- };
1227
- }
1228
- async function formatResults(results) {
1229
- for (const file of results) file.value = await formatWithPrettier(file.toString(), file.path === "" ? void 0 : file.path);
1230
- }
1231
- //#endregion
1232
- export { check, checkString, collapse, collapseString, createReadme as create, createReadmeInteractive as createInteractive, defineConfig, expand, expandString, getContextMetadata, getReadmeMetadata, loadConfig, mergeConfig, resetMetadataCaches, setLogger, strip, stripString };
1
+ import { _ as getReadmeMetadata, a as expand, b as setLogger, c as stripString, g as getContextMetadata, h as mergeConfig, i as collapseString, l as createReadme, m as loadConfig, n as checkString, o as expandString, p as defineConfig, r as collapse, s as strip, t as check, u as createReadmeInteractive, v as resetMetadataCaches } from "../lib-BkjaGFsm.js";
2
+
3
+ export { check, checkString, collapse, collapseString, createReadme as create, createReadmeInteractive as createInteractive, defineConfig, expand, expandString, getContextMetadata, getReadmeMetadata, loadConfig, mergeConfig, resetMetadataCaches, setLogger, strip, stripString };