mdat 3.2.0 → 3.2.2

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