@stephansama/auto-readme 0.2.1 → 0.2.3

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/index.cjs CHANGED
@@ -1,743 +1,683 @@
1
- "use strict";
1
+ //#region rolldown:runtime
2
2
  var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
8
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- run: () => run
34
- });
35
- module.exports = __toCommonJS(index_exports);
36
- var import_mdast_util_from_markdown2 = require("mdast-util-from-markdown");
37
- var cp2 = __toESM(require("child_process"), 1);
38
- var fsp3 = __toESM(require("fs/promises"), 1);
39
- var import_ora = __toESM(require("ora"), 1);
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
40
22
 
41
- // src/args.ts
42
- var import_debug = __toESM(require("debug"), 1);
43
- var import_yargs = __toESM(require("yargs"), 1);
44
- var import_helpers = require("yargs/helpers");
45
- var import_zod2 = __toESM(require("zod"), 1);
23
+ //#endregion
24
+ let mdast_util_from_markdown = require("mdast-util-from-markdown");
25
+ mdast_util_from_markdown = __toESM(mdast_util_from_markdown);
26
+ let node_child_process = require("node:child_process");
27
+ node_child_process = __toESM(node_child_process);
28
+ let node_fs_promises = require("node:fs/promises");
29
+ node_fs_promises = __toESM(node_fs_promises);
30
+ let ora = require("ora");
31
+ ora = __toESM(ora);
32
+ let debug = require("debug");
33
+ debug = __toESM(debug);
34
+ let yargs = require("yargs");
35
+ yargs = __toESM(yargs);
36
+ let yargs_helpers = require("yargs/helpers");
37
+ yargs_helpers = __toESM(yargs_helpers);
38
+ let zod = require("zod");
39
+ zod = __toESM(zod);
40
+ let mdast_comment_marker = require("mdast-comment-marker");
41
+ mdast_comment_marker = __toESM(mdast_comment_marker);
42
+ let __iarna_toml = require("@iarna/toml");
43
+ __iarna_toml = __toESM(__iarna_toml);
44
+ let cosmiconfig = require("cosmiconfig");
45
+ cosmiconfig = __toESM(cosmiconfig);
46
+ let deepmerge = require("deepmerge");
47
+ deepmerge = __toESM(deepmerge);
48
+ let __manypkg_get_packages = require("@manypkg/get-packages");
49
+ __manypkg_get_packages = __toESM(__manypkg_get_packages);
50
+ let node_fs = require("node:fs");
51
+ node_fs = __toESM(node_fs);
52
+ let node_path = require("node:path");
53
+ node_path = __toESM(node_path);
54
+ let pkg_types = require("pkg-types");
55
+ pkg_types = __toESM(pkg_types);
56
+ let yaml = require("yaml");
57
+ yaml = __toESM(yaml);
58
+ let zod2md = require("zod2md");
59
+ zod2md = __toESM(zod2md);
60
+ let fast_glob = require("fast-glob");
61
+ fast_glob = __toESM(fast_glob);
62
+ let remark = require("remark");
63
+ remark = __toESM(remark);
64
+ let remark_code_import = require("remark-code-import");
65
+ remark_code_import = __toESM(remark_code_import);
66
+ let remark_collapse = require("remark-collapse");
67
+ remark_collapse = __toESM(remark_collapse);
68
+ let remark_toc = require("remark-toc");
69
+ remark_toc = __toESM(remark_toc);
70
+ let remark_usage = require("remark-usage");
71
+ remark_usage = __toESM(remark_usage);
72
+ let vfile = require("vfile");
73
+ vfile = __toESM(vfile);
74
+ let handlebars = require("handlebars");
75
+ handlebars = __toESM(handlebars);
76
+ let markdown_table = require("markdown-table");
77
+ markdown_table = __toESM(markdown_table);
78
+ let mdast_zone = require("mdast-zone");
79
+ mdast_zone = __toESM(mdast_zone);
46
80
 
47
- // src/schema.js
48
- var import_zod = require("zod");
49
- var actionsSchema = import_zod.z.enum(["ACTION", "PKG", "USAGE", "WORKSPACE", "ZOD"]).describe("Comment action options");
50
- var formatsSchema = import_zod.z.enum(["LIST", "TABLE"]).default("TABLE").optional();
51
- var languageSchema = import_zod.z.enum(["JS", "RS"]).optional().default("JS");
52
- var headingsSchema = import_zod.z.enum([
53
- "default",
54
- "description",
55
- "devDependency",
56
- "downloads",
57
- "name",
58
- "private",
59
- "required",
60
- "version"
81
+ //#region src/schema.ts
82
+ const actionsSchema = zod.z.enum([
83
+ "ACTION",
84
+ "PKG",
85
+ "USAGE",
86
+ "WORKSPACE",
87
+ "ZOD"
88
+ ]).describe("Comment action options");
89
+ const formatsSchema = zod.z.enum(["LIST", "TABLE"]).default("TABLE").optional();
90
+ const languageSchema = zod.z.enum(["JS", "RS"]).optional().default("JS");
91
+ const headingsSchema = zod.z.enum([
92
+ "default",
93
+ "description",
94
+ "devDependency",
95
+ "downloads",
96
+ "name",
97
+ "private",
98
+ "required",
99
+ "version"
61
100
  ]).describe("Table heading options");
62
- var tableHeadingsSchema = import_zod.z.record(actionsSchema, headingsSchema.array().optional()).optional().describe("Table heading action configuration").default({
63
- ACTION: ["name", "required", "default", "description"],
64
- PKG: ["name", "version", "devDependency"],
65
- WORKSPACE: ["name", "version", "downloads", "description"],
66
- ZOD: []
101
+ const tableHeadingsSchema = zod.z.record(actionsSchema, headingsSchema.array().optional()).optional().describe("Table heading action configuration").default({
102
+ ACTION: [
103
+ "name",
104
+ "required",
105
+ "default",
106
+ "description"
107
+ ],
108
+ PKG: [
109
+ "name",
110
+ "version",
111
+ "devDependency"
112
+ ],
113
+ USAGE: [],
114
+ WORKSPACE: [
115
+ "name",
116
+ "version",
117
+ "downloads",
118
+ "description"
119
+ ],
120
+ ZOD: []
67
121
  });
68
- var templatesSchema = import_zod.z.object({
69
- downloadImage: import_zod.z.string().optional().default("https://img.shields.io/npm/dw/{{name}}?labelColor=211F1F"),
70
- emojis: import_zod.z.record(headingsSchema, import_zod.z.string()).optional().describe("Table heading emojis used when enabled").default({
71
- default: "\u2699\uFE0F",
72
- description: "\u{1F4DD}",
73
- devDependency: "\u{1F4BB}",
74
- downloads: "\u{1F4E5}",
75
- name: "\u{1F3F7}\uFE0F",
76
- private: "\u{1F512}",
77
- required: "",
78
- version: ""
79
- }),
80
- registryUrl: import_zod.z.string().optional().default("https://www.npmjs.com/package/{{name}}"),
81
- versionImage: import_zod.z.string().optional().default(
82
- "https://img.shields.io/npm/v/{{uri_name}}?logo=npm&logoColor=red&color=211F1F&labelColor=211F1F"
83
- )
122
+ const templatesSchema = zod.z.object({
123
+ downloadImage: zod.z.string().optional().default("https://img.shields.io/npm/dw/{{name}}?labelColor=211F1F"),
124
+ emojis: zod.z.record(headingsSchema, zod.z.string()).optional().describe("Table heading emojis used when enabled").default({
125
+ default: "⚙️",
126
+ description: "📝",
127
+ devDependency: "💻",
128
+ downloads: "📥",
129
+ name: "🏷️",
130
+ private: "🔒",
131
+ required: "",
132
+ version: ""
133
+ }),
134
+ registryUrl: zod.z.string().optional().default("https://www.npmjs.com/package/{{name}}"),
135
+ versionImage: zod.z.string().optional().default("https://img.shields.io/npm/v/{{uri_name}}?logo=npm&logoColor=red&color=211F1F&labelColor=211F1F")
84
136
  });
85
- var defaultTemplates = templatesSchema.parse({});
86
- var defaultTableHeadings = tableHeadingsSchema.parse(void 0);
87
- var _configSchema = import_zod.z.object({
88
- affectedRegexes: import_zod.z.string().array().optional().default([]),
89
- collapseHeadings: import_zod.z.string().array().optional().default([]),
90
- defaultLanguage: languageSchema.meta({
91
- alias: "l",
92
- description: "Default language to infer projects from"
93
- }),
94
- disableEmojis: import_zod.z.boolean().default(false).meta({
95
- alias: "e",
96
- description: "Whether or not to use emojis in markdown table headings"
97
- }),
98
- disableMarkdownHeadings: import_zod.z.boolean().default(false).meta({
99
- description: "Whether or not to display markdown headings"
100
- }),
101
- enablePrettier: import_zod.z.boolean().default(true).meta({
102
- description: "Whether or not to use prettier to format the files"
103
- }),
104
- enableToc: import_zod.z.boolean().default(false).meta({
105
- alias: "t",
106
- description: "generate table of contents for readmes"
107
- }),
108
- enableUsage: import_zod.z.boolean().optional().default(false).meta({
109
- description: "Whether or not to enable usage plugin"
110
- }),
111
- headings: tableHeadingsSchema.optional().default(defaultTableHeadings).describe("List of headings for different table outputs"),
112
- onlyReadmes: import_zod.z.boolean().default(true).meta({
113
- alias: "r",
114
- description: "Whether or not to only traverse readmes"
115
- }),
116
- onlyShowPublicPackages: import_zod.z.boolean().default(false).meta({
117
- alias: "p",
118
- description: "Only show public packages in workspaces"
119
- }),
120
- removeScope: import_zod.z.string().optional().default("").meta({
121
- description: "Remove common workspace scope"
122
- }),
123
- templates: templatesSchema.optional().default(defaultTemplates).describe(
124
- "Handlebars templates used to fuel list and table generation"
125
- ),
126
- tocHeading: import_zod.z.string().optional().default("Table of contents").meta({
127
- description: "Markdown heading used to generate table of contents"
128
- }),
129
- usageFile: import_zod.z.string().optional().default("").meta({
130
- description: "Workspace level usage file"
131
- }),
132
- usageHeading: import_zod.z.string().optional().default("Usage").meta({
133
- description: "Markdown heading used to generate usage example"
134
- }),
135
- verbose: import_zod.z.boolean().default(false).meta({
136
- alias: "v",
137
- description: "whether or not to display verbose logging"
138
- })
137
+ const defaultTemplates = templatesSchema.parse({});
138
+ const defaultTableHeadings = tableHeadingsSchema.parse(void 0);
139
+ const _configSchema = zod.z.object({
140
+ affectedRegexes: zod.z.string().array().optional().default([]),
141
+ collapseHeadings: zod.z.string().array().optional().default([]),
142
+ defaultLanguage: languageSchema.meta({
143
+ alias: "l",
144
+ description: "Default language to infer projects from"
145
+ }),
146
+ disableEmojis: zod.z.boolean().default(false).meta({
147
+ alias: "e",
148
+ description: "Whether or not to use emojis in markdown table headings"
149
+ }),
150
+ disableMarkdownHeadings: zod.z.boolean().default(false).meta({ description: "Whether or not to display markdown headings" }),
151
+ enablePrettier: zod.z.boolean().default(true).meta({ description: "Whether or not to use prettier to format the files" }),
152
+ enableToc: zod.z.boolean().default(false).meta({
153
+ alias: "t",
154
+ description: "generate table of contents for readmes"
155
+ }),
156
+ enableUsage: zod.z.boolean().optional().default(false).meta({ description: "Whether or not to enable usage plugin" }),
157
+ headings: tableHeadingsSchema.optional().default(defaultTableHeadings).describe("List of headings for different table outputs"),
158
+ onlyReadmes: zod.z.boolean().default(true).meta({
159
+ alias: "r",
160
+ description: "Whether or not to only traverse readmes"
161
+ }),
162
+ onlyShowPublicPackages: zod.z.boolean().default(false).meta({
163
+ alias: "p",
164
+ description: "Only show public packages in workspaces"
165
+ }),
166
+ removeScope: zod.z.string().optional().default("").meta({ description: "Remove common workspace scope" }),
167
+ templates: templatesSchema.optional().default(defaultTemplates).describe("Handlebars templates used to fuel list and table generation"),
168
+ tocHeading: zod.z.string().optional().default("Table of contents").meta({ description: "Markdown heading used to generate table of contents" }),
169
+ usageFile: zod.z.string().optional().default("").meta({ description: "Workspace level usage file" }),
170
+ usageHeading: zod.z.string().optional().default("Usage").meta({ description: "Markdown heading used to generate usage example" }),
171
+ verbose: zod.z.boolean().default(false).meta({
172
+ alias: "v",
173
+ description: "whether or not to display verbose logging"
174
+ })
139
175
  });
140
- var configSchema = _configSchema.optional();
176
+ const configSchema = _configSchema.optional();
141
177
 
142
- // src/args.ts
143
- var complexOptions = [
144
- "affectedRegexes",
145
- "collapseHeadings",
146
- "headings",
147
- "templates"
178
+ //#endregion
179
+ //#region src/args.ts
180
+ const complexOptions = [
181
+ "affectedRegexes",
182
+ "collapseHeadings",
183
+ "headings",
184
+ "templates"
148
185
  ];
149
- var args = {
150
- ...zodToYargs(),
151
- changes: {
152
- alias: "g",
153
- default: false,
154
- description: "Check only changed git files",
155
- type: "boolean"
156
- },
157
- check: {
158
- alias: "k",
159
- default: false,
160
- description: "Do not write to files. Only check for changes",
161
- type: "boolean"
162
- },
163
- config: { alias: "c", description: "Path to config file", type: "string" }
186
+ const args = {
187
+ ...zodToYargs(),
188
+ changes: {
189
+ alias: "g",
190
+ default: false,
191
+ description: "Check only changed git files",
192
+ type: "boolean"
193
+ },
194
+ check: {
195
+ alias: "k",
196
+ default: false,
197
+ description: "Do not write to files. Only check for changes",
198
+ type: "boolean"
199
+ },
200
+ config: {
201
+ alias: "c",
202
+ description: "Path to config file",
203
+ type: "string"
204
+ }
164
205
  };
165
206
  async function parseArgs() {
166
- const yargsInstance = (0, import_yargs.default)((0, import_helpers.hideBin)(process.argv)).options(args).help("h").alias("h", "help").epilogue(`--> @stephansama open-source ${(/* @__PURE__ */ new Date()).getFullYear()}`);
167
- const parsed = await yargsInstance.wrap(yargsInstance.terminalWidth()).parse();
168
- if (parsed.verbose) import_debug.default.enable("autoreadme*");
169
- return parsed;
207
+ const yargsInstance = (0, yargs.default)((0, yargs_helpers.hideBin)(process.argv)).options(args).help("h").alias("h", "help").epilogue(`--> @stephansama open-source ${(/* @__PURE__ */ new Date()).getFullYear()}`);
208
+ const parsed = await yargsInstance.wrap(yargsInstance.terminalWidth()).parse();
209
+ if (parsed.verbose) debug.default.enable("autoreadme*");
210
+ return parsed;
170
211
  }
171
212
  function zodToYargs() {
172
- const { shape } = configSchema.unwrap();
173
- const entries = Object.entries(shape).map(([key, value]) => {
174
- if (complexOptions.includes(key)) return [];
175
- if (value.def.innerType instanceof import_zod2.default.ZodObject) return [];
176
- const meta = value.meta();
177
- const { innerType } = value.def;
178
- const isBoolean = innerType instanceof import_zod2.default.ZodBoolean;
179
- const isNumber = innerType instanceof import_zod2.default.ZodNumber;
180
- const isArray = innerType instanceof import_zod2.default.ZodArray;
181
- const yargType = isArray && "array" || isNumber && "number" || isBoolean && "boolean" || "string";
182
- const options = {
183
- default: value.def.defaultValue,
184
- type: yargType
185
- };
186
- if (meta?.alias) options.alias = meta.alias;
187
- if (meta?.description) options.description = meta.description;
188
- return [key, options];
189
- });
190
- return Object.fromEntries(entries);
213
+ const { shape } = configSchema.unwrap();
214
+ const entries = Object.entries(shape).map(([key, value]) => {
215
+ if (complexOptions.includes(key)) return [];
216
+ if (value.def.innerType instanceof zod.default.ZodObject) return [];
217
+ const meta = value.meta();
218
+ const { innerType } = value.def;
219
+ const isBoolean = innerType instanceof zod.default.ZodBoolean;
220
+ const isNumber = innerType instanceof zod.default.ZodNumber;
221
+ const yargType = innerType instanceof zod.default.ZodArray && "array" || isNumber && "number" || isBoolean && "boolean" || "string";
222
+ const options = {
223
+ default: value.def.defaultValue,
224
+ type: yargType
225
+ };
226
+ if (meta?.alias) options.alias = meta.alias;
227
+ if (meta?.description) options.description = meta.description;
228
+ return [key, options];
229
+ });
230
+ return Object.fromEntries(entries);
191
231
  }
192
232
 
193
- // src/comment.ts
194
- var import_mdast_comment_marker = require("mdast-comment-marker");
195
-
196
- // src/log.ts
197
- var import_debug2 = __toESM(require("debug"), 1);
198
- var error = (0, import_debug2.default)("autoreadme:error");
199
- var info = (0, import_debug2.default)("autoreadme:info");
200
- var warn = (0, import_debug2.default)("autoreadme:warn");
233
+ //#endregion
234
+ //#region src/log.ts
235
+ const error = (0, debug.default)("autoreadme:error");
236
+ const info = (0, debug.default)("autoreadme:info");
237
+ const warn = (0, debug.default)("autoreadme:warn");
201
238
  function ERROR(...rest) {
202
- const [first, ...remaining] = rest;
203
- error(`${first} %O`, ...remaining);
239
+ const [first, ...remaining] = rest;
240
+ error(`${first} %O`, ...remaining);
204
241
  }
205
242
  function INFO(...rest) {
206
- const [first, ...remaining] = rest;
207
- info(`${first} %O`, ...remaining);
243
+ const [first, ...remaining] = rest;
244
+ info(`${first} %O`, ...remaining);
208
245
  }
209
246
  function WARN(...rest) {
210
- const [first, ...remaining] = rest;
211
- warn(`${first} %O`, ...remaining);
247
+ const [first, ...remaining] = rest;
248
+ warn(`${first} %O`, ...remaining);
212
249
  }
213
250
 
214
- // src/comment.ts
215
- var SEPARATOR = "-";
251
+ //#endregion
252
+ //#region src/comment.ts
253
+ const SEPARATOR = "-";
216
254
  function loadAstComments(root) {
217
- return root.children.map((child) => child.type === "html" && getComment(child)).filter((f) => f !== false);
255
+ return root.children.map((child) => child.type === "html" && getComment(child)).filter((f) => f !== false);
218
256
  }
219
257
  function parseComment(comment) {
220
- const input = trimComment(comment);
221
- const [type, ...parameters] = input.split(" ");
222
- const [first, second, third] = type.split(SEPARATOR);
223
- INFO("parsing inputs", { first, second, third });
224
- const languageInput = third ? first : void 0;
225
- const actionInput = third ? second : first;
226
- const formatInput = third ? third : second;
227
- const language = languageSchema.parse(languageInput);
228
- const action = actionsSchema.parse(actionInput);
229
- const format = formatsSchema.parse(formatInput);
230
- const isStart = comment.includes("start");
231
- const parsed = { action, format, isStart, language, parameters };
232
- INFO(`Parsed comment ${comment}`, parsed);
233
- return parsed;
258
+ const [type, ...parameters] = trimComment(comment).split(" ");
259
+ const [first, second, third] = type.split(SEPARATOR);
260
+ INFO("parsing inputs", {
261
+ first,
262
+ second,
263
+ third
264
+ });
265
+ const languageInput = third ? first : void 0;
266
+ const actionInput = third ? second : first;
267
+ const formatInput = third ? third : second;
268
+ const language = languageSchema.parse(languageInput);
269
+ const parsed = {
270
+ action: actionsSchema.parse(actionInput),
271
+ format: formatsSchema.parse(formatInput),
272
+ isStart: comment.includes("start"),
273
+ language,
274
+ parameters
275
+ };
276
+ INFO(`Parsed comment ${comment}`, parsed);
277
+ return parsed;
234
278
  }
235
- var startComment = "<!--";
236
- var endComment = "-->";
279
+ const startComment = "<!--";
280
+ const endComment = "-->";
237
281
  function trimComment(comment) {
238
- return comment.replace(startComment, "").replace(/start|end/, "").replace(endComment, "").trim();
282
+ return comment.replace(startComment, "").replace(/start|end/, "").replace(endComment, "").trim();
239
283
  }
240
284
  function getComment(comment) {
241
- if (!isComment(comment.value)) return false;
242
- const marker = (0, import_mdast_comment_marker.commentMarker)(comment);
243
- if (!marker) return false;
244
- return parseComment(comment.value);
285
+ if (!isComment(comment.value)) return false;
286
+ if (!(0, mdast_comment_marker.commentMarker)(comment)) return false;
287
+ return parseComment(comment.value);
245
288
  }
246
289
  function isComment(comment) {
247
- return comment.startsWith(startComment) && comment.endsWith(endComment);
290
+ return comment.startsWith(startComment) && comment.endsWith(endComment);
248
291
  }
249
292
 
250
- // src/config.ts
251
- var import_toml = __toESM(require("@iarna/toml"), 1);
252
- var import_cosmiconfig = require("cosmiconfig");
253
- var import_deepmerge = __toESM(require("deepmerge"), 1);
254
- var moduleName = "autoreadme";
255
- var searchPlaces = getSearchPlaces();
256
- var loaders = { [".toml"]: loadToml };
257
- async function loadConfig(args2) {
258
- const opts2 = { loaders, searchPlaces };
259
- if (args2.config) opts2.searchPlaces = [args2.config];
260
- const explorer = (0, import_cosmiconfig.cosmiconfig)(moduleName, opts2);
261
- const search = await explorer.search();
262
- if (!search) {
263
- const location = args2.config ? " at location: " + args2.config : "";
264
- WARN(`no config file found`, location);
265
- INFO("using default configuration");
266
- } else {
267
- INFO("found configuration file at: ", search.filepath);
268
- INFO("loaded cosmiconfig", search.config);
269
- }
270
- args2 = removeFalsy(args2);
271
- INFO("merging config with args", args2);
272
- return configSchema.parse(
273
- (0, import_deepmerge.default)(search?.config || {}, args2, {
274
- arrayMerge: (_, sourceArray) => sourceArray
275
- })
276
- );
293
+ //#endregion
294
+ //#region src/config.ts
295
+ const moduleName = "autoreadme";
296
+ const searchPlaces = getSearchPlaces();
297
+ const loaders = { [".toml"]: loadToml };
298
+ async function loadConfig(args$1) {
299
+ const opts$1 = {
300
+ loaders,
301
+ searchPlaces
302
+ };
303
+ if (args$1.config) opts$1.searchPlaces = [args$1.config];
304
+ const search = await (0, cosmiconfig.cosmiconfig)(moduleName, opts$1).search();
305
+ if (!search) {
306
+ WARN(`no config file found`, args$1.config ? " at location: " + args$1.config : "");
307
+ INFO("using default configuration");
308
+ } else {
309
+ INFO("found configuration file at: ", search.filepath);
310
+ INFO("loaded cosmiconfig", search.config);
311
+ }
312
+ args$1 = removeFalsy(args$1);
313
+ INFO("merging config with args", args$1);
314
+ return configSchema.parse((0, deepmerge.default)(search?.config || {}, args$1, { arrayMerge: (_, sourceArray) => sourceArray }));
277
315
  }
278
316
  function loadToml(_filepath, content) {
279
- return import_toml.default.parse(content);
317
+ return __iarna_toml.default.parse(content);
280
318
  }
281
319
  function getSearchPlaces() {
282
- return [
283
- ...(0, import_cosmiconfig.getDefaultSearchPlaces)(moduleName),
284
- `.${moduleName}rc.toml`,
285
- `.config/.${moduleName}rc`,
286
- `.config/${moduleName}rc.toml`,
287
- `.config/.${moduleName}rc.toml`,
288
- `.config/.${moduleName}rc.json`,
289
- `.config/.${moduleName}rc.yaml`,
290
- `.config/.${moduleName}rc.yml`
291
- ];
320
+ return [
321
+ ...(0, cosmiconfig.getDefaultSearchPlaces)(moduleName),
322
+ `.${moduleName}rc.toml`,
323
+ `.config/.${moduleName}rc`,
324
+ `.config/${moduleName}rc.toml`,
325
+ `.config/.${moduleName}rc.toml`,
326
+ `.config/.${moduleName}rc.json`,
327
+ `.config/.${moduleName}rc.yaml`,
328
+ `.config/.${moduleName}rc.yml`
329
+ ];
292
330
  }
293
331
  function removeFalsy(obj) {
294
- return Object.fromEntries(
295
- Object.entries(obj).map(([k, v]) => !v ? false : [k, v]).filter((e) => Boolean(e))
296
- );
332
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => !v ? false : [k, v]).filter((e) => Boolean(e)));
297
333
  }
298
334
 
299
- // src/data.ts
300
- var import_get_packages = require("@manypkg/get-packages");
301
- var fs2 = __toESM(require("fs"), 1);
302
- var fsp2 = __toESM(require("fs/promises"), 1);
303
- var path2 = __toESM(require("path"), 1);
304
- var import_pkg_types = require("pkg-types");
305
- var yaml = __toESM(require("yaml"), 1);
306
- var import_zod2md = require("zod2md");
307
-
308
- // src/utils.ts
309
- var import_fast_glob = __toESM(require("fast-glob"), 1);
310
- var cp = __toESM(require("child_process"), 1);
311
- var fs = __toESM(require("fs"), 1);
312
- var fsp = __toESM(require("fs/promises"), 1);
313
- var path = __toESM(require("path"), 1);
314
- var sh = String.raw;
315
- var opts = { encoding: "utf8" };
316
- var ignore = ["**/node_modules/**"];
317
- var matches = [
318
- /.*README\.md$/gi,
319
- /.*Cargo\.toml$/gi,
320
- /.*action\.ya?ml$/gi,
321
- /.*package\.json$/gi,
322
- /.*pnpm-workspace\.yaml$/gi
335
+ //#endregion
336
+ //#region src/utils.ts
337
+ const sh = String.raw;
338
+ const opts = { encoding: "utf8" };
339
+ const ignore = ["**/node_modules/**"];
340
+ const matches = [
341
+ /.*README\.md$/gi,
342
+ /.*Cargo\.toml$/gi,
343
+ /.*action\.ya?ml$/gi,
344
+ /.*package\.json$/gi,
345
+ /.*pnpm-workspace\.yaml$/gi
323
346
  ];
324
347
  async function fileExists(file) {
325
- return await fsp.access(file).then(() => true).catch(() => false);
348
+ return await node_fs_promises.access(file).then(() => true).catch(() => false);
326
349
  }
327
350
  function findAffectedMarkdowns(root, config) {
328
- const affected = cp.execSync(sh`git diff --cached --name-only --diff-filter=MACT`, opts).trim().split("\n").filter(Boolean);
329
- if (!affected.length) ERROR("no staged files found");
330
- if (config.affectedRegexes?.length) {
331
- INFO("adding the following expressions: ", config.affectedRegexes);
332
- }
333
- const allMatches = [
334
- ...matches,
335
- ...config.affectedRegexes?.map((r) => new RegExp(r)) || []
336
- ];
337
- INFO("Checking affected files against regexes", affected, allMatches);
338
- const eligible = affected.filter((a) => allMatches.some((m) => a.match(m)));
339
- INFO("Found the following eligible affected files", eligible);
340
- const md = eligible.map((e) => findNearestReadme(root, path.resolve(e)));
341
- const rootMd = path.join(root, "README.md");
342
- const dedupe = [...new Set(md), rootMd].filter(
343
- (s) => Boolean(s)
344
- );
345
- INFO("Found the following readmes", dedupe);
346
- return dedupe;
347
- }
348
- function findNearestReadme(gitRoot, inputFile, maxRotations = 15) {
349
- let dir = path.dirname(inputFile);
350
- let rotations = 0;
351
- while (true) {
352
- const option = path.join(dir, "README.md");
353
- if (fs.existsSync(option)) return option;
354
- const parent = path.dirname(dir);
355
- if (parent === dir || dir === gitRoot || ++rotations > maxRotations) {
356
- break;
357
- }
358
- dir = parent;
359
- }
360
- return null;
351
+ const affected = node_child_process.execSync(sh`git diff --cached --name-only --diff-filter=MACT`, opts).trim().split("\n").filter(Boolean);
352
+ if (!affected.length) ERROR("no staged files found");
353
+ if (config.affectedRegexes?.length) INFO("adding the following expressions: ", config.affectedRegexes);
354
+ const allMatches = [...matches, ...config.affectedRegexes?.map((r) => new RegExp(r)) || []];
355
+ INFO("Checking affected files against regexes", affected, allMatches);
356
+ const eligible = affected.filter((a) => allMatches.some((m) => a.match(m)));
357
+ INFO("Found the following eligible affected files", eligible);
358
+ const md = eligible.map((e) => findNearestReadme(root, node_path.resolve(e)));
359
+ const rootMd = node_path.join(root, "README.md");
360
+ const dedupe = [...new Set(md), rootMd].filter((s) => Boolean(s));
361
+ INFO("Found the following readmes", dedupe);
362
+ return dedupe;
361
363
  }
362
364
  function getGitRoot() {
363
- const root = cp.execSync(sh`git rev-parse --show-toplevel`, opts).trim();
364
- if (!root) {
365
- throw new Error("must be ran within a git directory.");
366
- }
367
- INFO("found git root at location: ", root);
368
- return root;
365
+ const root = node_child_process.execSync(sh`git rev-parse --show-toplevel`, opts).trim();
366
+ if (!root) throw new Error("must be ran within a git directory.");
367
+ INFO("found git root at location: ", root);
368
+ return root;
369
369
  }
370
370
  async function getMarkdownPaths(cwd, config) {
371
- const pattern = `**/${config?.onlyReadmes ? "README" : "*"}.md`;
372
- const readmes = await (0, import_fast_glob.default)(pattern, { cwd, ignore });
373
- return readmes.map((readme) => path.resolve(cwd, readme));
371
+ return (await (0, fast_glob.default)(`**/${config?.onlyReadmes ? "README" : "*"}.md`, {
372
+ cwd,
373
+ ignore
374
+ })).map((readme) => node_path.resolve(cwd, readme));
374
375
  }
375
376
  async function getPrettierPaths(paths) {
376
- return await Promise.all(
377
- paths.map(async (file) => {
378
- const stats = await fsp.lstat(file);
379
- const isSymbolicLink = stats.isSymbolicLink();
380
- if (!isSymbolicLink) return file;
381
- const symlink = await fsp.readlink(file);
382
- return path.join(path.dirname(file), symlink);
383
- })
384
- );
377
+ return await Promise.all(paths.map(async (file) => {
378
+ if (!(await node_fs_promises.lstat(file)).isSymbolicLink()) return file;
379
+ const symlink = await node_fs_promises.readlink(file);
380
+ return node_path.join(node_path.dirname(file), symlink);
381
+ }));
382
+ }
383
+ function findNearestReadme(gitRoot, inputFile, maxRotations = 15) {
384
+ let dir = node_path.dirname(inputFile);
385
+ let rotations = 0;
386
+ while (true) {
387
+ const option = node_path.join(dir, "README.md");
388
+ if (node_fs.existsSync(option)) return option;
389
+ const parent = node_path.dirname(dir);
390
+ if (parent === dir || dir === gitRoot || ++rotations > maxRotations) break;
391
+ dir = parent;
392
+ }
393
+ return null;
385
394
  }
386
395
 
387
- // src/data.ts
396
+ //#endregion
397
+ //#region src/data.ts
388
398
  function createFindParameter(parameterList) {
389
- return function(parameterName) {
390
- return parameterList?.find((p) => p.startsWith(parameterName))?.replace(parameterName + "=", "")?.replace(/"/gi, "")?.replace(/_/gi, " ");
391
- };
399
+ return function(parameterName) {
400
+ return parameterList?.find((p) => p.startsWith(parameterName))?.replace(parameterName + "=", "")?.replace(/"/gi, "")?.replace(/_/gi, " ");
401
+ };
392
402
  }
393
403
  async function loadActionData(actions, file, root) {
394
- const startActions = actions.filter((action) => action.isStart);
395
- return await Promise.all(
396
- startActions.map(async (action) => {
397
- const find = createFindParameter(action.parameters);
398
- switch (action.action) {
399
- case "ACTION": {
400
- const baseDir = path2.dirname(file);
401
- const actionYaml = await loadActionYaml(baseDir);
402
- return {
403
- action: action.action,
404
- actionYaml,
405
- parameters: action.parameters
406
- };
407
- }
408
- case "PKG": {
409
- const inputPath = find("path");
410
- const filename = inputPath ? path2.resolve(path2.dirname(file), inputPath) : path2.dirname(file);
411
- const pkgJson = await (0, import_pkg_types.readPackageJSON)(filename);
412
- return {
413
- action: action.action,
414
- parameters: action.parameters,
415
- pkgJson
416
- };
417
- }
418
- case "USAGE": {
419
- return {
420
- action: action.action,
421
- parameters: action.parameters
422
- };
423
- }
424
- case "WORKSPACE": {
425
- const workspaces = await (0, import_get_packages.getPackages)(process.cwd());
426
- const pnpmPath = path2.resolve(root, "pnpm-workspace.yaml");
427
- const isPnpm = fs2.existsSync(pnpmPath);
428
- return {
429
- action: action.action,
430
- isPnpm,
431
- parameters: action.parameters,
432
- root,
433
- workspaces
434
- };
435
- }
436
- case "ZOD": {
437
- if (action.format === "LIST") {
438
- throw new Error("cannot display zod in list format");
439
- }
440
- const inputPath = find("path");
441
- if (!inputPath) {
442
- const error2 = `no path found for zod table at markdown file ${file}`;
443
- throw new Error(error2);
444
- }
445
- const body = await (0, import_zod2md.zod2md)({
446
- entry: path2.resolve(path2.dirname(file), inputPath),
447
- title: find("title") || "Zod Schema"
448
- });
449
- return {
450
- action: action.action,
451
- body,
452
- parameters: action.parameters
453
- };
454
- }
455
- default:
456
- throw new Error("feature not yet implemented");
457
- }
458
- })
459
- );
404
+ const startActions = actions.filter((action) => action.isStart);
405
+ return await Promise.all(startActions.map(async (action) => {
406
+ const find = createFindParameter(action.parameters);
407
+ switch (action.action) {
408
+ case "ACTION": {
409
+ const actionYaml = await loadActionYaml(node_path.dirname(file));
410
+ return {
411
+ action: action.action,
412
+ actionYaml,
413
+ parameters: action.parameters
414
+ };
415
+ }
416
+ case "PKG": {
417
+ const inputPath = find("path");
418
+ const pkgJson = await (0, pkg_types.readPackageJSON)(inputPath ? node_path.resolve(node_path.dirname(file), inputPath) : node_path.dirname(file));
419
+ return {
420
+ action: action.action,
421
+ parameters: action.parameters,
422
+ pkgJson
423
+ };
424
+ }
425
+ case "USAGE": return {
426
+ action: action.action,
427
+ parameters: action.parameters
428
+ };
429
+ case "WORKSPACE": {
430
+ const workspaces = await (0, __manypkg_get_packages.getPackages)(process.cwd());
431
+ const pnpmPath = node_path.resolve(root, "pnpm-workspace.yaml");
432
+ const isPnpm = node_fs.existsSync(pnpmPath);
433
+ return {
434
+ action: action.action,
435
+ isPnpm,
436
+ parameters: action.parameters,
437
+ root,
438
+ workspaces
439
+ };
440
+ }
441
+ case "ZOD": {
442
+ if (action.format === "LIST") throw new Error("cannot display zod in list format");
443
+ const inputPath = find("path");
444
+ if (!inputPath) {
445
+ const error$1 = `no path found for zod table at markdown file ${file}`;
446
+ throw new Error(error$1);
447
+ }
448
+ const body = await (0, zod2md.zod2md)({
449
+ entry: node_path.resolve(node_path.dirname(file), inputPath),
450
+ title: find("title") || "Zod Schema"
451
+ });
452
+ return {
453
+ action: action.action,
454
+ body,
455
+ parameters: action.parameters
456
+ };
457
+ }
458
+ default: throw new Error("feature not yet implemented");
459
+ }
460
+ }));
460
461
  }
461
462
  async function loadActionYaml(baseDir) {
462
- const actionYmlPath = path2.resolve(baseDir, "action.yml");
463
- const actionYamlPath = path2.resolve(baseDir, "action.yaml");
464
- const actualPath = await fileExists(actionYamlPath) && actionYamlPath || await fileExists(actionYmlPath) && actionYmlPath;
465
- if (!actualPath) {
466
- const locations = [actionYmlPath, actionYamlPath];
467
- const error2 = `no yaml file found at locations: ${locations}`;
468
- throw new Error(error2);
469
- }
470
- const actionFile = await fsp2.readFile(actualPath, { encoding: "utf8" });
471
- return yaml.parse(actionFile);
463
+ const actionYmlPath = node_path.resolve(baseDir, "action.yml");
464
+ const actionYamlPath = node_path.resolve(baseDir, "action.yaml");
465
+ const actualPath = await fileExists(actionYamlPath) && actionYamlPath || await fileExists(actionYmlPath) && actionYmlPath;
466
+ if (!actualPath) {
467
+ const error$1 = `no yaml file found at locations: ${[actionYmlPath, actionYamlPath]}`;
468
+ throw new Error(error$1);
469
+ }
470
+ const actionFile = await node_fs_promises.readFile(actualPath, { encoding: "utf8" });
471
+ return yaml.parse(actionFile);
472
472
  }
473
473
 
474
- // src/pipeline.ts
475
- var path4 = __toESM(require("path"), 1);
476
- var import_remark = require("remark");
477
- var import_remark_code_import = __toESM(require("remark-code-import"), 1);
478
- var import_remark_collapse = __toESM(require("remark-collapse"), 1);
479
- var import_remark_toc = __toESM(require("remark-toc"), 1);
480
- var import_remark_usage = __toESM(require("remark-usage"), 1);
481
- var import_vfile = require("vfile");
482
-
483
- // src/plugin.ts
484
- var import_handlebars = __toESM(require("handlebars"), 1);
485
- var import_markdown_table = require("markdown-table");
486
- var import_mdast_util_from_markdown = require("mdast-util-from-markdown");
487
- var import_mdast_zone = require("mdast-zone");
488
- var import_node_path = __toESM(require("path"), 1);
474
+ //#endregion
475
+ //#region src/plugin.ts
489
476
  function createHeading(headings, disableEmojis = false, emojis = defaultTemplates.emojis) {
490
- return headings.map(
491
- (h) => `${disableEmojis ? "" : emojis[h] + " "}${h?.at(0)?.toUpperCase() + h?.slice(1)}`
492
- );
477
+ return headings.map((h) => `${disableEmojis ? "" : emojis[h] + " "}${h?.at(0)?.toUpperCase() + h?.slice(1)}`);
493
478
  }
494
479
  function wrapRequired(required, input) {
495
- if (!required) return input;
496
- return `<b>*${input}</b>`;
480
+ if (!required) return input;
481
+ return `<b>*${input}</b>`;
497
482
  }
498
- var autoReadmeRemarkPlugin = (config, data) => (tree) => {
499
- (0, import_mdast_zone.zone)(tree, /.*ZOD.*/gi, function(start, _, end) {
500
- const zod = data.find((d) => d?.action === "ZOD");
501
- if (!zod?.body) {
502
- throw new Error("unable to load zod body");
503
- }
504
- const ast = (0, import_mdast_util_from_markdown.fromMarkdown)(zod.body);
505
- return [start, ast, end];
506
- });
507
- (0, import_mdast_zone.zone)(tree, /.*ACTION.*/gi, function(start, _, end) {
508
- const value = start.type === "html" && start.value;
509
- const options = value && parseComment(value);
510
- if (!options) throw new Error("not able to parse comment");
511
- const first = data.find((d) => d?.action === "ACTION");
512
- const inputs = first?.actionYaml?.inputs || {};
513
- const heading = `### ${config.disableEmojis ? "" : "\u{1F9F0}"} actions`;
514
- if (options.format === "LIST") {
515
- const body2 = `${heading}
516
- ` + Object.entries(inputs).sort((a) => a[1].required ? -1 : 1).map(([key, value2]) => {
517
- return `- ${wrapRequired(value2.required, key)}: (default: ${value2.default})
518
-
519
- ${value2.description}`;
520
- }).join("\n");
521
- const ast2 = (0, import_mdast_util_from_markdown.fromMarkdown)(body2);
522
- return [start, ast2, end];
523
- }
524
- const headings = config.headings?.ACTION?.length && config.headings.ACTION || defaultTableHeadings.ACTION;
525
- const table = (0, import_markdown_table.markdownTable)([
526
- createHeading(
527
- headings,
528
- config.disableEmojis,
529
- config.templates?.emojis
530
- ),
531
- ...Object.entries(inputs).map(
532
- ([k, v]) => headings.map((heading2) => v[heading2] || k).map(String)
533
- )
534
- ]);
535
- const body = [heading, "", table].join("\n");
536
- const ast = (0, import_mdast_util_from_markdown.fromMarkdown)(body);
537
- return [start, ast, end];
538
- });
539
- (0, import_mdast_zone.zone)(tree, /.*WORKSPACE.*/gi, function(start, _, end) {
540
- const value = start.type === "html" && start.value;
541
- const comment = value && parseComment(value);
542
- const workspace = data.find((d) => d?.action === "WORKSPACE");
543
- const templates = loadTemplates(config.templates);
544
- const packages = workspace?.workspaces?.packages || [];
545
- const headings = config.headings?.WORKSPACE?.length && config.headings?.WORKSPACE || defaultTableHeadings.WORKSPACE;
546
- if (comment && comment.format === "LIST") {
547
- }
548
- const tableHeadings = createHeading(
549
- headings,
550
- config.disableEmojis,
551
- config.templates?.emojis
552
- );
553
- const table = (0, import_markdown_table.markdownTable)([
554
- tableHeadings,
555
- ...packages.filter(
556
- (pkg) => config.onlyShowPublicPackages ? !pkg.packageJson.private : true
557
- ).map((pkg) => {
558
- const { name } = pkg.packageJson;
559
- return headings.map((heading2) => {
560
- if (heading2 === "name") {
561
- const scoped = config.removeScope ? name.replace(config.removeScope, "") : name;
562
- return `[${scoped}](${import_node_path.default.relative(
563
- process.cwd(),
564
- import_node_path.default.resolve(pkg.dir, "README.md")
565
- )})`;
566
- }
567
- if (heading2 === "version") {
568
- return `![npm version image](${templates.versionImage(
569
- { uri_name: encodeURIComponent(name) }
570
- )})`;
571
- }
572
- if (heading2 === "downloads") {
573
- return `![npm downloads](${templates.downloadImage(
574
- { name }
575
- )})`;
576
- }
577
- if (heading2 === "description") {
578
- return pkg.packageJson?.description;
579
- }
580
- return ``;
581
- });
582
- })
583
- ]);
584
- const heading = `### ${config.disableEmojis ? "" : "\u{1F3ED}"} workspace`;
585
- const body = [heading, "", table].join("\n");
586
- const ast = (0, import_mdast_util_from_markdown.fromMarkdown)(body);
587
- return [start, ast, end];
588
- });
589
- (0, import_mdast_zone.zone)(tree, /.*PKG.*/gi, function(start, _, end) {
590
- const value = start.type === "html" && start.value;
591
- const comment = value && parseComment(value);
592
- const first = data.find((d) => d?.action === "PKG");
593
- const templates = loadTemplates(config.templates);
594
- const headings = config.headings?.PKG?.length && config.headings?.PKG || defaultTableHeadings.PKG;
595
- if (comment && comment.format === "LIST") {
596
- const ast = (0, import_mdast_util_from_markdown.fromMarkdown)("");
597
- return [start, ast, end];
598
- }
599
- function mapDependencies(isDev) {
600
- return function([name, version]) {
601
- const url = templates.registryUrl({ name });
602
- return headings.map((key) => {
603
- if (key === "devDependency") {
604
- if (config.disableEmojis) {
605
- return `\`${isDev}\``;
606
- }
607
- return `${isDev ? "\u2328\uFE0F" : "\u{1F465}"}`;
608
- }
609
- if (key === "name") {
610
- return `[${name}](${url})`;
611
- }
612
- if (key === "version") {
613
- if (["workspace", "catalog", "*"].some(
614
- (type) => version.includes(type)
615
- )) {
616
- return `\`${version}\``;
617
- }
618
- return `![npm version](${templates.versionImage({ uri_name: encodeURIComponent(name) })})`;
619
- }
620
- });
621
- };
622
- }
623
- const { dependencies = {}, devDependencies = {} } = first?.pkgJson || {};
624
- const table = (0, import_markdown_table.markdownTable)([
625
- createHeading(
626
- headings,
627
- config.disableEmojis,
628
- config.templates?.emojis
629
- ),
630
- ...Object.entries(devDependencies).map(mapDependencies(true)),
631
- ...Object.entries(dependencies).map(mapDependencies(false))
632
- ]);
633
- const heading = `### ${config.disableEmojis ? "" : "\u{1F4E6}"} packages`;
634
- const body = [heading, "", table].join("\n");
635
- const tableAst = (0, import_mdast_util_from_markdown.fromMarkdown)(body);
636
- return [start, tableAst, end];
637
- });
483
+ const autoReadmeRemarkPlugin = (config, data) => (tree) => {
484
+ (0, mdast_zone.zone)(tree, /.*ZOD.*/gi, function(start, _, end) {
485
+ const zod$1 = data.find((d) => d?.action === "ZOD");
486
+ if (!zod$1?.body) throw new Error("unable to load zod body");
487
+ return [
488
+ start,
489
+ (0, mdast_util_from_markdown.fromMarkdown)(zod$1.body),
490
+ end
491
+ ];
492
+ });
493
+ (0, mdast_zone.zone)(tree, /.*ACTION.*/gi, function(start, _, end) {
494
+ const value = start.type === "html" && start.value;
495
+ const options = value && parseComment(value);
496
+ if (!options) throw new Error("not able to parse comment");
497
+ const inputs = data.find((d) => d?.action === "ACTION")?.actionYaml?.inputs || {};
498
+ const heading = `### ${config.disableEmojis ? "" : "🧰"} actions`;
499
+ if (options.format === "LIST") return [
500
+ start,
501
+ (0, mdast_util_from_markdown.fromMarkdown)(`${heading}\n` + Object.entries(inputs).sort((a) => a[1].required ? -1 : 1).map(([key, value$1]) => {
502
+ return `- ${wrapRequired(value$1.required, key)}: (default: ${value$1.default})\n\n${value$1.description}`;
503
+ }).join("\n")),
504
+ end
505
+ ];
506
+ const headings = config.headings?.ACTION?.length && config.headings.ACTION || defaultTableHeadings.ACTION;
507
+ return [
508
+ start,
509
+ (0, mdast_util_from_markdown.fromMarkdown)([
510
+ heading,
511
+ "",
512
+ (0, markdown_table.markdownTable)([createHeading(headings, config.disableEmojis, config.templates?.emojis), ...Object.entries(inputs).map(([k, v]) => headings.map((heading$1) => v[heading$1] || k).map(String))])
513
+ ].join("\n")),
514
+ end
515
+ ];
516
+ });
517
+ (0, mdast_zone.zone)(tree, /.*WORKSPACE.*/gi, function(start, _, end) {
518
+ const value = start.type === "html" && start.value;
519
+ const comment = value && parseComment(value);
520
+ const workspace = data.find((d) => d?.action === "WORKSPACE");
521
+ const templates = loadTemplates(config.templates);
522
+ const packages = workspace?.workspaces?.packages || [];
523
+ const headings = config.headings?.WORKSPACE?.length && config.headings?.WORKSPACE || defaultTableHeadings.WORKSPACE;
524
+ if (comment && comment.format === "LIST") {}
525
+ const table = (0, markdown_table.markdownTable)([createHeading(headings, config.disableEmojis, config.templates?.emojis), ...packages.filter((pkg) => config.onlyShowPublicPackages ? !pkg.packageJson.private : true).map((pkg) => {
526
+ const { name } = pkg.packageJson;
527
+ return headings.map((heading) => {
528
+ if (heading === "name") return `[${config.removeScope ? name.replace(config.removeScope, "") : name}](${node_path.default.relative(process.cwd(), node_path.default.resolve(pkg.dir, "README.md"))})`;
529
+ if (heading === "version") return `![npm version image](${templates.versionImage({ uri_name: encodeURIComponent(name) })})`;
530
+ if (heading === "downloads") return `![npm downloads](${templates.downloadImage({ name })})`;
531
+ if (heading === "description") return pkg.packageJson?.description;
532
+ return ``;
533
+ });
534
+ })]);
535
+ return [
536
+ start,
537
+ (0, mdast_util_from_markdown.fromMarkdown)([
538
+ `### ${config.disableEmojis ? "" : "🏭"} workspace`,
539
+ "",
540
+ table
541
+ ].join("\n")),
542
+ end
543
+ ];
544
+ });
545
+ (0, mdast_zone.zone)(tree, /.*PKG.*/gi, function(start, _, end) {
546
+ const value = start.type === "html" && start.value;
547
+ const comment = value && parseComment(value);
548
+ const first = data.find((d) => d?.action === "PKG");
549
+ const templates = loadTemplates(config.templates);
550
+ const headings = config.headings?.PKG?.length && config.headings?.PKG || defaultTableHeadings.PKG;
551
+ if (comment && comment.format === "LIST") return [
552
+ start,
553
+ (0, mdast_util_from_markdown.fromMarkdown)(""),
554
+ end
555
+ ];
556
+ function mapDependencies(isDev) {
557
+ return function([name, version]) {
558
+ const url = templates.registryUrl({ name });
559
+ return headings.map((key) => {
560
+ if (key === "devDependency") {
561
+ if (config.disableEmojis) return `\`${isDev}\``;
562
+ return `${isDev ? "⌨️" : "👥"}`;
563
+ }
564
+ if (key === "name") return `[${name}](${url})`;
565
+ if (key === "version") {
566
+ if ([
567
+ "workspace",
568
+ "catalog",
569
+ "*"
570
+ ].some((type) => version.includes(type))) return `\`${version}\``;
571
+ return `![npm version](${templates.versionImage({ uri_name: encodeURIComponent(name) })})`;
572
+ }
573
+ });
574
+ };
575
+ }
576
+ const { dependencies = {}, devDependencies = {} } = first?.pkgJson || {};
577
+ const table = (0, markdown_table.markdownTable)([
578
+ createHeading(headings, config.disableEmojis, config.templates?.emojis),
579
+ ...Object.entries(devDependencies).map(mapDependencies(true)),
580
+ ...Object.entries(dependencies).map(mapDependencies(false))
581
+ ]);
582
+ return [
583
+ start,
584
+ (0, mdast_util_from_markdown.fromMarkdown)([
585
+ `### ${config.disableEmojis ? "" : "📦"} packages`,
586
+ "",
587
+ table
588
+ ].join("\n")),
589
+ end
590
+ ];
591
+ });
638
592
  };
639
593
  function loadTemplates(templates) {
640
- if (!templates) throw new Error("failed to load templates");
641
- return Object.fromEntries(
642
- Object.entries(templates).map(([key, value]) => {
643
- if (typeof value !== "string") return [];
644
- return [key, import_handlebars.default.compile(value)];
645
- })
646
- );
594
+ if (!templates) throw new Error("failed to load templates");
595
+ return Object.fromEntries(Object.entries(templates).map(([key, value]) => {
596
+ if (typeof value !== "string") return [];
597
+ return [key, handlebars.default.compile(value)];
598
+ }));
647
599
  }
648
600
 
649
- // src/pipeline.ts
650
- async function parse2(file, filepath, root, config, data) {
651
- const pipeline = (0, import_remark.remark)().use(autoReadmeRemarkPlugin, config, data).use(import_remark_code_import.default, {});
652
- const usage = data.find((d) => d.action === "USAGE");
653
- if (usage?.action === "USAGE" || config.enableUsage) {
654
- const find = createFindParameter(usage?.parameters || []);
655
- const examplePath = find("path");
656
- const dirname4 = path4.dirname(filepath);
657
- const resolvePath = examplePath && path4.resolve(dirname4, examplePath);
658
- const relativeProjectPath = config.usageFile && path4.relative(root, path4.resolve(dirname4, config.usageFile));
659
- const example = examplePath && resolvePath && path4.relative(root, resolvePath) || relativeProjectPath || void 0;
660
- if (example && await fileExists(example)) {
661
- INFO("generating usage section");
662
- pipeline.use(import_remark_usage.default, {
663
- example,
664
- heading: config.usageHeading
665
- });
666
- } else {
667
- WARN("not able to find example file for readme", filepath, example);
668
- }
669
- }
670
- if (config.enableToc) {
671
- INFO("generating table of contents section");
672
- pipeline.use(import_remark_toc.default, { heading: config.tocHeading });
673
- }
674
- if (config.enableToc || config.collapseHeadings?.length) {
675
- const additional = config.collapseHeadings?.length ? config.collapseHeadings : [];
676
- const headings = [...additional, config.tocHeading];
677
- pipeline.use(import_remark_collapse.default, {
678
- test: {
679
- ignoreFinalDefinitions: true,
680
- test: (value, _) => {
681
- return headings.some((i) => value.trim() === i?.trim());
682
- }
683
- }
684
- });
685
- }
686
- const vfile = new import_vfile.VFile({ path: path4.resolve(filepath), value: file });
687
- const markdown = await pipeline.process(vfile);
688
- return markdown.toString();
601
+ //#endregion
602
+ //#region src/pipeline.ts
603
+ async function parse(file, filepath, root, config, data) {
604
+ const pipeline = (0, remark.remark)().use(autoReadmeRemarkPlugin, config, data).use(remark_code_import.default, {});
605
+ const usage = data.find((d) => d.action === "USAGE");
606
+ if (usage?.action === "USAGE" || config.enableUsage) {
607
+ const examplePath = createFindParameter(usage?.parameters || [])("path");
608
+ const dirname = node_path.dirname(filepath);
609
+ const resolvePath = examplePath && node_path.resolve(dirname, examplePath);
610
+ const relativeProjectPath = config.usageFile && node_path.relative(root, node_path.resolve(dirname, config.usageFile));
611
+ const example = examplePath && resolvePath && node_path.relative(root, resolvePath) || relativeProjectPath || void 0;
612
+ if (example && await fileExists(example)) {
613
+ INFO("generating usage section");
614
+ pipeline.use(remark_usage.default, {
615
+ example,
616
+ heading: config.usageHeading
617
+ });
618
+ } else WARN("not able to find example file for readme", filepath, example);
619
+ }
620
+ if (config.enableToc) {
621
+ INFO("generating table of contents section");
622
+ pipeline.use(remark_toc.default, { heading: config.tocHeading });
623
+ }
624
+ if (config.enableToc || config.collapseHeadings?.length) {
625
+ const headings = [...config.collapseHeadings?.length ? config.collapseHeadings : [], config.tocHeading];
626
+ pipeline.use(remark_collapse.default, { test: {
627
+ ignoreFinalDefinitions: true,
628
+ test: (value, _) => {
629
+ return headings.some((i) => value.trim() === i?.trim());
630
+ }
631
+ } });
632
+ }
633
+ const vfile$1 = new vfile.VFile({
634
+ path: node_path.resolve(filepath),
635
+ value: file
636
+ });
637
+ return (await pipeline.process(vfile$1)).toString();
689
638
  }
690
639
 
691
- // src/index.ts
640
+ //#endregion
641
+ //#region src/index.ts
692
642
  async function run() {
693
- const args2 = await parseArgs();
694
- const config = await loadConfig(args2) || {};
695
- INFO("Loaded the following configuration:", config);
696
- const root = getGitRoot();
697
- const isAffected = args2.changes && "affected";
698
- INFO(`Loading ${!isAffected ? "all " : "affected "}files`);
699
- const paths = isAffected ? findAffectedMarkdowns(root, config) : await getMarkdownPaths(root, config);
700
- INFO("Loaded the following files:", paths.join("\n"));
701
- const type = args2.onlyReadmes ? "readmes" : "all markdown files";
702
- if (!paths.length) {
703
- return ERROR(`no ${isAffected} readmes found to update`);
704
- }
705
- const spinner = !args2.verbose && (0, import_ora.default)(`Updating ${type}`).start();
706
- await Promise.all(
707
- paths.map(async (path5) => {
708
- const file = await fsp3.readFile(path5, { encoding: "utf8" });
709
- const actions = (() => {
710
- const ast = (0, import_mdast_util_from_markdown2.fromMarkdown)(file);
711
- return loadAstComments(ast);
712
- })();
713
- if (!actions.length) {
714
- WARN(`no action comments found in`, path5);
715
- if (!config.enableUsage || !config.enableToc) {
716
- return ERROR("no action or plugins found");
717
- } else {
718
- INFO("plugins enabled. continuing parsing", path5);
719
- }
720
- }
721
- const data = await loadActionData(actions, path5, root);
722
- INFO("Loaded comment action data", data);
723
- const content = await parse2(file, path5, root, config, data);
724
- await fsp3.writeFile(path5, content);
725
- })
726
- );
727
- const opts2 = { stdio: "inherit" };
728
- if (config.enablePrettier) {
729
- INFO("formatting with prettier");
730
- const prettierPaths = await getPrettierPaths(paths);
731
- cp2.execFileSync("prettier", ["--write", ...prettierPaths], opts2);
732
- }
733
- if (isAffected) {
734
- INFO("adding affected files to git stage");
735
- cp2.execFileSync("git", ["add", ...paths], opts2);
736
- }
737
- if (spinner) spinner.stop();
643
+ const args$1 = await parseArgs();
644
+ const config = await loadConfig(args$1) || {};
645
+ INFO("Loaded the following configuration:", config);
646
+ const root = getGitRoot();
647
+ const isAffected = args$1.changes && "affected";
648
+ INFO(`Loading ${!isAffected ? "all " : "affected "}files`);
649
+ const paths = isAffected ? findAffectedMarkdowns(root, config) : await getMarkdownPaths(root, config);
650
+ INFO("Loaded the following files:", paths.join("\n"));
651
+ const type = args$1.onlyReadmes ? "readmes" : "all markdown files";
652
+ if (!paths.length) return ERROR(`no ${isAffected} readmes found to update`);
653
+ const spinner = !args$1.verbose && (0, ora.default)(`Updating ${type}`).start();
654
+ await Promise.all(paths.map(async (path$1) => {
655
+ const file = await node_fs_promises.readFile(path$1, { encoding: "utf8" });
656
+ const actions = (() => {
657
+ return loadAstComments((0, mdast_util_from_markdown.fromMarkdown)(file));
658
+ })();
659
+ if (!actions.length) {
660
+ WARN(`no action comments found in`, path$1);
661
+ if (!config.enableUsage || !config.enableToc) return ERROR("no action or plugins found");
662
+ else INFO("plugins enabled. continuing parsing", path$1);
663
+ }
664
+ const data = await loadActionData(actions, path$1, root);
665
+ INFO("Loaded comment action data", data);
666
+ const content = await parse(file, path$1, root, config, data);
667
+ await node_fs_promises.writeFile(path$1, content);
668
+ }));
669
+ const opts$1 = { stdio: "inherit" };
670
+ if (config.enablePrettier) {
671
+ INFO("formatting with prettier");
672
+ const prettierPaths = await getPrettierPaths(paths);
673
+ node_child_process.execFileSync("prettier", ["--write", ...prettierPaths], opts$1);
674
+ }
675
+ if (isAffected) {
676
+ INFO("adding affected files to git stage");
677
+ node_child_process.execFileSync("git", ["add", ...paths], opts$1);
678
+ }
679
+ if (spinner) spinner.stop();
738
680
  }
739
- // Annotate the CommonJS export names for ESM import in node:
740
- 0 && (module.exports = {
741
- run
742
- });
743
- //# sourceMappingURL=index.cjs.map
681
+
682
+ //#endregion
683
+ exports.run = run;