sveld 0.26.2 → 0.27.0

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/lib/plugin.js DELETED
@@ -1,269 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = pluginSveld;
7
- exports.generateBundle = generateBundle;
8
- exports.writeOutput = writeOutput;
9
- const node_fs_1 = require("node:fs");
10
- const promises_1 = require("node:fs/promises");
11
- const node_path_1 = require("node:path");
12
- const compiler_1 = require("svelte/compiler");
13
- const svelte_preprocess_1 = require("svelte-preprocess");
14
- const tinyglobby_1 = require("tinyglobby");
15
- const ComponentParser_1 = __importDefault(require("./ComponentParser"));
16
- const get_svelte_entry_1 = require("./get-svelte-entry");
17
- const parse_exports_1 = require("./parse-exports");
18
- const path_1 = require("./path");
19
- const writer_json_1 = __importDefault(require("./writer/writer-json"));
20
- const writer_markdown_1 = __importDefault(require("./writer/writer-markdown"));
21
- const writer_ts_definitions_1 = __importDefault(require("./writer/writer-ts-definitions"));
22
- const STYLE_TAG_REGEX = /<style.+?<\/style>/gims;
23
- const HYPHEN_REGEX = /-/g;
24
- function pluginSveld(opts) {
25
- let result;
26
- let input;
27
- return {
28
- name: "vite-plugin-sveld",
29
- apply: "build",
30
- enforce: "post",
31
- buildStart() {
32
- input = (0, get_svelte_entry_1.getSvelteEntry)(opts?.entry);
33
- },
34
- async generateBundle() {
35
- if (input != null) {
36
- result = await generateBundle(input, opts?.glob === true);
37
- }
38
- },
39
- writeBundle() {
40
- if (input != null)
41
- writeOutput(result, opts || {}, input);
42
- },
43
- };
44
- }
45
- /**
46
- * Generates component documentation bundle from Svelte source files.
47
- *
48
- * Parses exports, discovers components (optionally via glob), and processes
49
- * all Svelte files to extract component metadata. Returns both exported
50
- * components (for JSON/Markdown) and all components (for TypeScript definitions).
51
- *
52
- * @param input - Entry point file or directory containing Svelte components
53
- * @param glob - Whether to glob for all .svelte files in the directory
54
- * @returns Bundle result containing exports, components, and allComponentsForTypes
55
- *
56
- * @example
57
- * ```ts
58
- * // Generate from single file:
59
- * const result = await generateBundle("./src/App.svelte", false);
60
- *
61
- * // Generate from directory with glob:
62
- * const result = await generateBundle("./src", true);
63
- * ```
64
- */
65
- async function generateBundle(input, glob) {
66
- const isFile = (0, node_fs_1.lstatSync)(input).isFile();
67
- const dir = isFile ? (0, node_path_1.dirname)(input) : input;
68
- /**
69
- * Only parse exports if input is a file.
70
- * Directory inputs don't have a single entry point to parse exports from.
71
- */
72
- let exports = {};
73
- if (isFile) {
74
- const entry = (0, node_fs_1.readFileSync)(input, "utf-8");
75
- exports = (0, parse_exports_1.parseExports)(entry, dir);
76
- }
77
- const allComponents = { ...exports };
78
- if (glob) {
79
- for (const file of (0, tinyglobby_1.globSync)([`${dir}/**/*.svelte`])) {
80
- const moduleName = (0, node_path_1.parse)(file).name.replace(HYPHEN_REGEX, "");
81
- const source = (0, path_1.normalizeSeparators)(`./${(0, node_path_1.relative)(dir, file)}`);
82
- if (exports[moduleName]) {
83
- exports[moduleName].source = source;
84
- }
85
- if (allComponents[moduleName]) {
86
- allComponents[moduleName].source = source;
87
- }
88
- else {
89
- allComponents[moduleName] = { source, default: false };
90
- }
91
- }
92
- }
93
- const components = new Map();
94
- const allComponentsForTypes = new Map();
95
- const exportEntries = Object.entries(exports);
96
- const allComponentEntries = Object.entries(allComponents);
97
- const uniqueFilePaths = new Set();
98
- for (const [, entry] of exportEntries) {
99
- const filePath = entry.source;
100
- const { ext } = (0, node_path_1.parse)(filePath);
101
- if (ext === ".svelte") {
102
- uniqueFilePaths.add((0, node_path_1.resolve)(dir, filePath));
103
- }
104
- }
105
- for (const [, entry] of allComponentEntries) {
106
- const filePath = entry.source;
107
- const { ext } = (0, node_path_1.parse)(filePath);
108
- if (ext === ".svelte") {
109
- uniqueFilePaths.add((0, node_path_1.resolve)(dir, filePath));
110
- }
111
- }
112
- const fileContents = await Promise.all(Array.from(uniqueFilePaths).map(async (filePath) => {
113
- try {
114
- const content = await (0, promises_1.readFile)(filePath, "utf-8");
115
- return { path: filePath, content };
116
- }
117
- catch (error) {
118
- console.warn(`Warning: Failed to read file ${filePath}:`, error);
119
- return { path: filePath, content: null };
120
- }
121
- }));
122
- const fileMap = new Map(fileContents.map(({ path, content }) => [path, content]));
123
- /**
124
- * Helper function to process a single component.
125
- *
126
- * Reads the component file, preprocesses it (removes styles, processes TypeScript),
127
- * and parses it to extract component metadata. Handles file read errors gracefully.
128
- *
129
- * @param entry - Export entry tuple [exportName, exportInfo]
130
- * @param entries - All export entries for context
131
- * @param fileMap - Map of file paths to their contents
132
- * @returns Component documentation or null if processing failed
133
- *
134
- * @example
135
- * ```ts
136
- * const result = await processComponent(
137
- * ["Button", { source: "./Button.svelte", default: true }],
138
- * allEntries,
139
- * fileMap
140
- * );
141
- * // Returns: { moduleName: "Button", filePath: "./Button.svelte", props: [...], ... }
142
- * ```
143
- */
144
- const processComponent = async ([exportName, entry], entries, fileMap) => {
145
- const filePath = entry.source;
146
- const { ext, name } = (0, node_path_1.parse)(filePath);
147
- let moduleName = exportName;
148
- if (entries.length === 1 && exportName === "default") {
149
- moduleName = name;
150
- }
151
- if (ext === ".svelte") {
152
- const resolvedPath = (0, node_path_1.resolve)(dir, filePath);
153
- const source = fileMap.get(resolvedPath);
154
- if (source === null || source === undefined) {
155
- /**
156
- * File was not found or failed to read, skip this component.
157
- * This can happen if the file doesn't exist or if there was an error
158
- * reading it (already logged as a warning).
159
- */
160
- return null;
161
- }
162
- const { code: processed } = await (0, compiler_1.preprocess)(source, [(0, svelte_preprocess_1.typescript)(), (0, svelte_preprocess_1.replace)([[STYLE_TAG_REGEX, ""]])], {
163
- filename: (0, node_path_1.basename)(filePath),
164
- });
165
- const parser = new ComponentParser_1.default();
166
- const parsed = parser.parseSvelteComponent(processed, {
167
- moduleName,
168
- filePath,
169
- });
170
- return {
171
- moduleName,
172
- filePath,
173
- ...parsed,
174
- };
175
- }
176
- return null;
177
- };
178
- /**
179
- * Process exported components (for metadata/JSON/Markdown).
180
- * Only components that are explicitly exported are included in the
181
- * components map for JSON and Markdown output.
182
- */
183
- const componentPromises = exportEntries.map((entry) => processComponent(entry, exportEntries, fileMap));
184
- /**
185
- * Process all components (for .d.ts generation).
186
- * All discovered components are included in allComponentsForTypes
187
- * to ensure TypeScript definitions are generated for all components,
188
- * even if they're not explicitly exported.
189
- */
190
- const allComponentPromises = allComponentEntries.map((entry) => processComponent(entry, allComponentEntries, fileMap));
191
- const [results, allResults] = await Promise.all([Promise.all(componentPromises), Promise.all(allComponentPromises)]);
192
- for (const result of results) {
193
- if (result) {
194
- components.set(result.moduleName, result);
195
- }
196
- }
197
- for (const result of allResults) {
198
- if (result) {
199
- allComponentsForTypes.set(result.moduleName, result);
200
- }
201
- }
202
- return {
203
- exports,
204
- components,
205
- allComponentsForTypes,
206
- };
207
- }
208
- /**
209
- * Writes output files based on plugin options.
210
- *
211
- * Generates TypeScript definitions, JSON metadata, and/or Markdown documentation
212
- * based on the options provided. Uses different component sets for different
213
- * output types to match expected behavior.
214
- *
215
- * @param result - Bundle result containing exports and component documentation
216
- * @param opts - Plugin options determining what outputs to generate
217
- * @param input - Input file path for determining input directory
218
- *
219
- * @example
220
- * ```ts
221
- * writeOutput(result, {
222
- * types: true,
223
- * json: true,
224
- * markdown: true
225
- * }, "./src/App.svelte");
226
- * // Generates: types/*.d.ts, COMPONENT_API.json, COMPONENT_INDEX.md
227
- * ```
228
- */
229
- function writeOutput(result, opts, input) {
230
- const inputDir = (0, node_path_1.dirname)(input);
231
- if (opts?.types !== false) {
232
- /**
233
- * Use allComponentsForTypes to generate .d.ts for all discovered components.
234
- * This ensures TypeScript definitions are available for all components,
235
- * not just exported ones, which is useful for type checking.
236
- */
237
- (0, writer_ts_definitions_1.default)(result.allComponentsForTypes, {
238
- outDir: "types",
239
- preamble: "",
240
- ...opts?.typesOptions,
241
- exports: result.exports,
242
- inputDir,
243
- });
244
- }
245
- if (opts?.json) {
246
- /**
247
- * Use components (exported only) for JSON metadata.
248
- * JSON output should only include components that are actually exported,
249
- * matching the public API surface.
250
- */
251
- (0, writer_json_1.default)(result.components, {
252
- outFile: "COMPONENT_API.json",
253
- ...opts?.jsonOptions,
254
- input,
255
- inputDir,
256
- });
257
- }
258
- if (opts?.markdown) {
259
- /**
260
- * Use components (exported only) for Markdown documentation.
261
- * Documentation should only include exported components that are
262
- * part of the public API.
263
- */
264
- (0, writer_markdown_1.default)(result.components, {
265
- outFile: "COMPONENT_INDEX.md",
266
- ...opts?.markdownOptions,
267
- });
268
- }
269
- }
@@ -1,198 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.clearConfigCache = clearConfigCache;
4
- exports.resolvePathAliasAbsolute = resolvePathAliasAbsolute;
5
- exports.resolvePathAlias = resolvePathAlias;
6
- const node_fs_1 = require("node:fs");
7
- const node_path_1 = require("node:path");
8
- const path_1 = require("./path");
9
- const configCache = new Map();
10
- const pathPatternRegexCache = new Map();
11
- const COMMENT_PATTERN = /\/\*[\s\S]*?\*\/|\/\/.*/g;
12
- const REGEX_SPECIAL_CHARS = /[.+?^${}()|[\]\\]/g;
13
- /**
14
- * Clears the TypeScript/JavaScript config cache.
15
- *
16
- * Useful for testing or when config files are modified during runtime.
17
- * Forces re-reading of config files on next resolution.
18
- */
19
- function clearConfigCache() {
20
- configCache.clear();
21
- }
22
- /**
23
- * Finds the nearest tsconfig.json or jsconfig.json starting from a directory.
24
- *
25
- * Walks up the directory tree from the start directory until it finds
26
- * a config file or reaches the filesystem root.
27
- *
28
- * @param startDir - The directory to start searching from
29
- * @returns The path to the config file, or null if not found
30
- *
31
- * @example
32
- * ```ts
33
- * // From ./src/components/Button.svelte
34
- * findConfig("./src/components")
35
- * // Returns: "./tsconfig.json" (if found in project root)
36
- * ```
37
- */
38
- function findConfig(startDir) {
39
- let dir = startDir;
40
- const root = (0, node_path_1.resolve)(dir, "/");
41
- while (dir !== root) {
42
- for (const configName of ["tsconfig.json", "jsconfig.json"]) {
43
- const configPath = (0, node_path_1.join)(dir, configName);
44
- if ((0, node_fs_1.existsSync)(configPath)) {
45
- return configPath;
46
- }
47
- }
48
- dir = (0, node_path_1.dirname)(dir);
49
- }
50
- return null;
51
- }
52
- function parseConfig(configPath) {
53
- if (configCache.has(configPath)) {
54
- return configCache.get(configPath) ?? null;
55
- }
56
- try {
57
- const content = (0, node_fs_1.readFileSync)(configPath, "utf-8");
58
- const jsonContent = content.replace(COMMENT_PATTERN, "");
59
- const config = JSON.parse(jsonContent);
60
- if (config.extends) {
61
- const baseConfigPath = (0, node_path_1.isAbsolute)(config.extends) ? config.extends : (0, node_path_1.resolve)((0, node_path_1.dirname)(configPath), config.extends);
62
- const fullBaseConfigPath = baseConfigPath.endsWith(".json") ? baseConfigPath : `${baseConfigPath}.json`;
63
- if ((0, node_fs_1.existsSync)(fullBaseConfigPath)) {
64
- const baseConfig = parseConfig(fullBaseConfigPath);
65
- if (baseConfig) {
66
- config.compilerOptions = {
67
- ...baseConfig.compilerOptions,
68
- ...config.compilerOptions,
69
- paths: {
70
- ...baseConfig.compilerOptions?.paths,
71
- ...config.compilerOptions?.paths,
72
- },
73
- };
74
- }
75
- }
76
- }
77
- configCache.set(configPath, config);
78
- return config;
79
- }
80
- catch {
81
- configCache.set(configPath, null);
82
- return null;
83
- }
84
- }
85
- /**
86
- * Resolves a path alias to an absolute file system path for reading files.
87
- *
88
- * Uses TypeScript/JavaScript config path mappings to resolve aliases like
89
- * `$lib/components` to actual file system paths. Handles wildcard patterns
90
- * and baseUrl resolution.
91
- *
92
- * @param importPath - The import path that may contain an alias
93
- * @param fromDir - The directory to resolve relative to (for finding config)
94
- * @returns The absolute resolved path, or original path if resolution fails
95
- *
96
- * @example
97
- * ```ts
98
- * // With tsconfig.json: { "paths": { "$lib/*": ["./src/lib/*"] } }
99
- * resolvePathAliasAbsolute("$lib/utils", "./src")
100
- * // Returns: "/absolute/path/to/src/lib/utils"
101
- *
102
- * resolvePathAliasAbsolute("./relative", "./src")
103
- * // Returns: "./relative" (unchanged, not an alias)
104
- * ```
105
- */
106
- function resolvePathAliasAbsolute(importPath, fromDir) {
107
- if (importPath.startsWith(".") || importPath.startsWith("/")) {
108
- return importPath;
109
- }
110
- const configPath = findConfig(fromDir);
111
- if (!configPath) {
112
- return importPath;
113
- }
114
- const config = parseConfig(configPath);
115
- if (!config?.compilerOptions?.paths) {
116
- return importPath;
117
- }
118
- const { baseUrl = ".", paths } = config.compilerOptions;
119
- const configDir = (0, node_path_1.dirname)(configPath);
120
- const resolvedBaseUrl = (0, node_path_1.resolve)(configDir, baseUrl);
121
- // Try to match against path patterns
122
- for (const [pattern, mappings] of Object.entries(paths)) {
123
- /**
124
- * Convert TS path pattern to regex.
125
- * Examples:
126
- * - "$lib/*" -> /^\$lib\/(.*)$/
127
- * - "$lib" -> /^\$lib$/
128
- * - "@components/*" -> /^@components\/(.*)$/
129
- */
130
- let regex = pathPatternRegexCache.get(pattern);
131
- if (!regex) {
132
- /**
133
- * Escape special regex chars but keep * for replacement.
134
- * The * wildcard is converted to a capture group for substitution.
135
- */
136
- const escapedPattern = pattern
137
- .split("*")
138
- .map((part) => part.replace(REGEX_SPECIAL_CHARS, "\\$&"))
139
- .join("(.*)");
140
- regex = new RegExp(`^${escapedPattern}$`);
141
- pathPatternRegexCache.set(pattern, regex);
142
- }
143
- const match = importPath.match(regex);
144
- if (match) {
145
- // TypeScript uses the first matching pattern
146
- const mapping = mappings[0];
147
- if (!mapping)
148
- continue;
149
- // Replace * in mapping with captured groups (e.g., "$lib/*" matching "$lib/utils" -> "utils")
150
- let resolvedPath = mapping;
151
- for (let i = 1; i < match.length; i++) {
152
- resolvedPath = resolvedPath.replace("*", match[i]);
153
- }
154
- // Resolve relative to baseUrl from tsconfig
155
- const fullPath = (0, node_path_1.resolve)(resolvedBaseUrl, resolvedPath);
156
- return fullPath;
157
- }
158
- }
159
- return importPath;
160
- }
161
- /**
162
- * Resolves a path alias and converts it to a relative path from fromDir.
163
- *
164
- * This is used for storing paths in the exports object for output generation.
165
- * Unlike `resolvePathAliasAbsolute`, this returns a relative path suitable
166
- * for use in generated export statements.
167
- *
168
- * @param importPath - The import path that may contain an alias
169
- * @param fromDir - The directory to resolve relative to
170
- * @returns A relative path (prefixed with ./ if needed), or original path if resolution fails
171
- *
172
- * @example
173
- * ```ts
174
- * // With alias "$lib/utils" -> "./src/lib/utils"
175
- * resolvePathAlias("$lib/utils", "./src")
176
- * // Returns: "./lib/utils"
177
- *
178
- * resolvePathAlias("./Button.svelte", "./src")
179
- * // Returns: "./Button.svelte" (unchanged, not an alias)
180
- * ```
181
- */
182
- function resolvePathAlias(importPath, fromDir) {
183
- if (importPath.startsWith(".") || importPath.startsWith("/")) {
184
- return importPath;
185
- }
186
- const absolutePath = resolvePathAliasAbsolute(importPath, fromDir);
187
- if (absolutePath === importPath) {
188
- return importPath;
189
- }
190
- let relativePath = (0, node_path_1.relative)(fromDir, absolutePath);
191
- /**
192
- * Normalize path separators to forward slashes for consistency across platforms.
193
- * Windows uses backslashes, but we want forward slashes in generated code
194
- * for cross-platform compatibility.
195
- */
196
- relativePath = (0, path_1.normalizeSeparators)(relativePath);
197
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
198
- }
package/lib/sveld.js DELETED
@@ -1,33 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sveld = sveld;
4
- const get_svelte_entry_1 = require("./get-svelte-entry");
5
- const plugin_1 = require("./plugin");
6
- /**
7
- * Main entry point for programmatic sveld usage.
8
- *
9
- * Generates component documentation from Svelte source files and writes
10
- * output files based on the provided options. Can be used as a library
11
- * in addition to the CLI interface.
12
- *
13
- * @param opts - Options for generating documentation
14
- * @returns A promise that resolves when documentation generation is complete
15
- *
16
- * @example
17
- * ```ts
18
- * await sveld({
19
- * input: "./src",
20
- * types: true,
21
- * json: true,
22
- * markdown: true,
23
- * glob: true
24
- * });
25
- * ```
26
- */
27
- async function sveld(opts) {
28
- const input = (0, get_svelte_entry_1.getSvelteEntry)(opts?.input);
29
- if (input === null)
30
- return;
31
- const result = await (0, plugin_1.generateBundle)(input, opts?.glob === true);
32
- (0, plugin_1.writeOutput)(result, opts || {}, input);
33
- }
@@ -1,70 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MarkdownWriterBaseImpl = void 0;
4
- const markdown_format_utils_1 = require("./markdown-format-utils");
5
- /**
6
- * Base class containing shared markdown writing logic.
7
- * This can be extended or used via composition.
8
- */
9
- class MarkdownWriterBaseImpl {
10
- sourceParts = [];
11
- hasToC = false;
12
- toc = [];
13
- get source() {
14
- return this.sourceParts.join("");
15
- }
16
- appendLineBreaks() {
17
- this.sourceParts.push("\n\n");
18
- return this;
19
- }
20
- append(type, raw) {
21
- switch (type) {
22
- case "h1":
23
- case "h2":
24
- case "h3":
25
- case "h4":
26
- case "h5":
27
- case "h6": {
28
- const length = Number(type.slice(-1));
29
- this.sourceParts.push(`${"#".repeat(length)} ${raw}`);
30
- if (this.hasToC && type === "h2") {
31
- this.toc.push({
32
- array: Array.from({ length: (length - 1) * 2 }),
33
- raw: raw ?? "",
34
- });
35
- }
36
- break;
37
- }
38
- case "quote":
39
- this.sourceParts.push(`> ${raw}`);
40
- break;
41
- case "p":
42
- this.sourceParts.push(raw ?? "");
43
- break;
44
- case "divider":
45
- this.sourceParts.push("---");
46
- break;
47
- case "raw":
48
- this.sourceParts.push(raw ?? "");
49
- break;
50
- }
51
- if (type !== "raw")
52
- this.appendLineBreaks();
53
- return this;
54
- }
55
- tableOfContents() {
56
- this.sourceParts.push("<!-- __TOC__ -->");
57
- this.hasToC = true;
58
- this.appendLineBreaks();
59
- return this;
60
- }
61
- end() {
62
- const source = this.sourceParts.join("");
63
- return source.replace("<!-- __TOC__ -->", this.toc
64
- .map(({ array, raw }) => {
65
- return `${array.join(" ")} - [${raw}](#${raw.toLowerCase().replace(markdown_format_utils_1.BACKTICK_REGEX, "").replace(markdown_format_utils_1.WHITESPACE_REGEX, "-")})`;
66
- })
67
- .join("\n"));
68
- }
69
- }
70
- exports.MarkdownWriterBaseImpl = MarkdownWriterBaseImpl;
@@ -1,104 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createJsonWriter = createJsonWriter;
4
- exports.createTypeScriptWriter = createTypeScriptWriter;
5
- const promises_1 = require("node:fs/promises");
6
- const node_path_1 = require("node:path");
7
- const prettier_1 = require("prettier");
8
- /**
9
- * Base writer class for formatting and writing files.
10
- *
11
- * Handles file formatting using Prettier and file system operations.
12
- * Automatically creates directories as needed and formats content
13
- * before writing.
14
- *
15
- * @example
16
- * ```ts
17
- * const writer = new Writer({ parser: "typescript", printWidth: 80 });
18
- * await writer.write("./dist/index.d.ts", "export type Props = {};");
19
- * ```
20
- */
21
- class Writer {
22
- options;
23
- /**
24
- * Creates a new Writer instance.
25
- *
26
- * @param options - Writer configuration options
27
- */
28
- constructor(options) {
29
- this.options = options;
30
- }
31
- /**
32
- * Formats raw content using Prettier.
33
- *
34
- * Applies formatting based on the configured parser and print width.
35
- * Returns the original content if formatting fails.
36
- *
37
- * @param raw - The raw content to format
38
- * @returns Formatted content, or original content if formatting fails
39
- *
40
- * @example
41
- * ```ts
42
- * const formatted = await writer.format("export type Props={}");
43
- * // Returns: "export type Props = {};\n"
44
- * ```
45
- */
46
- async format(raw) {
47
- try {
48
- const result = await (0, prettier_1.format)(raw, this.options);
49
- return result;
50
- }
51
- catch (error) {
52
- console.error(error);
53
- return raw;
54
- }
55
- }
56
- /**
57
- * Writes formatted content to a file.
58
- *
59
- * Creates the directory structure if needed, formats the content,
60
- * and writes it to the specified file path.
61
- *
62
- * @param filePath - The path where the file should be written
63
- * @param raw - The raw content to format and write
64
- *
65
- * @example
66
- * ```ts
67
- * await writer.write("./dist/index.d.ts", "export type Props={}");
68
- * // Creates ./dist/index.d.ts with formatted content
69
- * ```
70
- */
71
- async write(filePath, raw) {
72
- await (0, promises_1.mkdir)((0, node_path_1.parse)(filePath).dir, { recursive: true });
73
- await (0, promises_1.writeFile)(filePath, await this.format(raw));
74
- }
75
- }
76
- exports.default = Writer;
77
- /**
78
- * Creates a Writer instance configured for JSON files.
79
- *
80
- * @returns A Writer instance with JSON parser and 80 character print width
81
- *
82
- * @example
83
- * ```ts
84
- * const writer = createJsonWriter();
85
- * await writer.write("data.json", JSON.stringify({ key: "value" }));
86
- * ```
87
- */
88
- function createJsonWriter() {
89
- return new Writer({ parser: "json", printWidth: 80 });
90
- }
91
- /**
92
- * Creates a Writer instance configured for TypeScript files.
93
- *
94
- * @returns A Writer instance with TypeScript parser and 80 character print width
95
- *
96
- * @example
97
- * ```ts
98
- * const writer = createTypeScriptWriter();
99
- * await writer.write("index.d.ts", "export type Props={};");
100
- * ```
101
- */
102
- function createTypeScriptWriter() {
103
- return new Writer({ parser: "typescript", printWidth: 80 });
104
- }