@node-minify/utils 10.2.0 → 10.4.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/LICENSE +1 -1
- package/dist/buildArgs.js +2 -2
- package/dist/buildArgs.js.map +1 -1
- package/dist/compressSingleFile.d.ts +1 -1
- package/dist/compressSingleFile.d.ts.map +1 -1
- package/dist/compressSingleFile.js +6 -32
- package/dist/compressSingleFile.js.map +1 -1
- package/dist/compressor-resolver.d.ts +76 -0
- package/dist/compressor-resolver.d.ts.map +1 -0
- package/dist/compressor-resolver.js +183 -0
- package/dist/compressor-resolver.js.map +1 -0
- package/dist/deleteFile.d.ts +1 -1
- package/dist/deleteFile.js +2 -2
- package/dist/deleteFile.js.map +1 -1
- package/dist/deprecation.d.ts +1 -1
- package/dist/deprecation.js +1 -1
- package/dist/deprecation.js.map +1 -1
- package/dist/ensureStringContent.d.ts +1 -1
- package/dist/ensureStringContent.js +1 -1
- package/dist/ensureStringContent.js.map +1 -1
- package/dist/{error-Ck87RwDD.js → error-CUgKxOvI.js} +5 -3
- package/dist/error-CUgKxOvI.js.map +1 -0
- package/dist/error.d.ts +2 -1
- package/dist/error.d.ts.map +1 -1
- package/dist/error.js +1 -1
- package/dist/errors.d.ts +27 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +32 -0
- package/dist/errors.js.map +1 -0
- package/dist/getContentFromFiles.d.ts +1 -1
- package/dist/getContentFromFiles.js +4 -4
- package/dist/getContentFromFiles.js.map +1 -1
- package/dist/getFilesizeBrotliInBytes.d.ts +26 -0
- package/dist/getFilesizeBrotliInBytes.d.ts.map +1 -0
- package/dist/getFilesizeBrotliInBytes.js +63 -0
- package/dist/getFilesizeBrotliInBytes.js.map +1 -0
- package/dist/getFilesizeGzippedInBytes.d.ts +14 -8
- package/dist/getFilesizeGzippedInBytes.d.ts.map +1 -1
- package/dist/getFilesizeGzippedInBytes.js +41 -18
- package/dist/getFilesizeGzippedInBytes.js.map +1 -1
- package/dist/getFilesizeInBytes.d.ts +1 -1
- package/dist/getFilesizeInBytes.js +1 -1
- package/dist/getFilesizeInBytes.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.js +9 -5
- package/dist/isImageFile.d.ts +16 -0
- package/dist/isImageFile.d.ts.map +1 -0
- package/dist/isImageFile.js +35 -0
- package/dist/isImageFile.js.map +1 -0
- package/dist/{isValidFile-DnWJtlKA.js → isValidFile-COstpeyW.js} +4 -4
- package/dist/isValidFile-COstpeyW.js.map +1 -0
- package/dist/isValidFile.d.ts +1 -1
- package/dist/isValidFile.js +1 -1
- package/dist/prettyBytes.d.ts +1 -1
- package/dist/prettyBytes.js +2 -2
- package/dist/prettyBytes.js.map +1 -1
- package/dist/readFile.d.ts +13 -2
- package/dist/readFile.d.ts.map +1 -1
- package/dist/readFile.js +19 -3
- package/dist/readFile.js.map +1 -1
- package/dist/run.d.ts +4 -4
- package/dist/run.js +48 -37
- package/dist/run.js.map +1 -1
- package/dist/setFileNameMin.d.ts +1 -1
- package/dist/setFileNameMin.js +2 -2
- package/dist/setFileNameMin.js.map +1 -1
- package/dist/setPublicFolder.d.ts +1 -1
- package/dist/setPublicFolder.js +1 -1
- package/dist/setPublicFolder.js.map +1 -1
- package/dist/{types-BUlX1Zbb.d.ts → types-CWBFD3au.d.ts} +16 -2
- package/dist/types-CWBFD3au.d.ts.map +1 -0
- package/dist/types.d.ts +1 -1
- package/dist/wildcards.d.ts +1 -1
- package/dist/wildcards.js +1 -1
- package/dist/wildcards.js.map +1 -1
- package/dist/writeFile-mfUS3rMz.js +96 -0
- package/dist/writeFile-mfUS3rMz.js.map +1 -0
- package/dist/writeFile.d.ts +20 -2
- package/dist/writeFile.d.ts.map +1 -1
- package/dist/writeFile.js +2 -2
- package/package.json +2 -2
- package/dist/error-Ck87RwDD.js.map +0 -1
- package/dist/isValidFile-DnWJtlKA.js.map +0 -1
- package/dist/types-BUlX1Zbb.d.ts.map +0 -1
- package/dist/writeFile-BRfs9FqY.js +0 -39
- package/dist/writeFile-BRfs9FqY.js.map +0 -1
package/dist/readFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readFile.js","names":[],"sources":["../src/readFile.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-
|
|
1
|
+
{"version":3,"file":"readFile.js","names":["readFilePromise"],"sources":["../src/readFile.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { readFile as readFilePromise } from \"node:fs/promises\";\nimport { FileOperationError } from \"./error.ts\";\n\n/**\n * Read content from file.\n * @param file - Path to file\n * @param asBuffer - If true, return Buffer; if false, return string (default: false)\n * @returns File content as string or Buffer\n * @throws {FileOperationError} If file doesn't exist or reading fails\n * @example\n * // Read as string\n * const content = readFile('file.txt');\n *\n * // Read as Buffer (for binary files like images)\n * const buffer = readFile('image.png', true);\n */\nexport function readFile(file: string): string;\nexport function readFile(file: string, asBuffer: true): Buffer;\nexport function readFile(file: string, asBuffer: false): string;\nexport function readFile(file: string, asBuffer?: boolean): string | Buffer;\n/**\n * Read a file from disk and return its contents as a UTF-8 string by default or as a raw Buffer.\n *\n * @param file - Path to the file to read.\n * @param asBuffer - If `true`, return a raw `Buffer`; if `false` or omitted, return the file decoded as a UTF-8 `string`.\n * @returns A `Buffer` when `asBuffer` is `true`, otherwise the file content as a UTF-8 `string`.\n * @throws FileOperationError when the file cannot be read; the original error is attached as the cause.\n */\nexport function readFile(file: string, asBuffer?: boolean): string | Buffer {\n try {\n return asBuffer ? readFileSync(file) : readFileSync(file, \"utf8\");\n } catch (error) {\n throw new FileOperationError(\n \"read\",\n file,\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Read content from file asynchronously.\n * @param file - Path to file\n * @param asBuffer - If true, return Buffer; if false, return string (default: false)\n * @returns File content as string or Buffer\n * @throws {FileOperationError} If file doesn't exist or reading fails\n */\nexport async function readFileAsync(file: string): Promise<string>;\nexport async function readFileAsync(\n file: string,\n asBuffer: true\n): Promise<Buffer>;\nexport async function readFileAsync(\n file: string,\n asBuffer: false\n): Promise<string>;\nexport async function readFileAsync(\n file: string,\n asBuffer?: boolean\n): Promise<string | Buffer>;\n/**\n * Read a file from disk asynchronously and return its contents as a UTF-8 string by default or as a raw Buffer.\n *\n * @param file - Path to the file to read.\n * @param asBuffer - If `true`, return a raw `Buffer`; if `false` or omitted, return the file decoded as a UTF-8 `string`.\n * @returns A `Buffer` when `asBuffer` is `true`, otherwise the file content as a UTF-8 `string`.\n * @throws FileOperationError when the file cannot be read; the original error is attached as the cause.\n */\nexport async function readFileAsync(\n file: string,\n asBuffer?: boolean\n): Promise<string | Buffer> {\n try {\n return asBuffer\n ? await readFilePromise(file)\n : await readFilePromise(file, \"utf8\");\n } catch (error) {\n throw new FileOperationError(\n \"read\",\n file,\n error instanceof Error ? error : undefined\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCA,SAAgB,SAAS,MAAc,UAAqC;AACxE,KAAI;AACA,SAAO,WAAW,aAAa,KAAK,GAAG,aAAa,MAAM,OAAO;UAC5D,OAAO;AACZ,QAAM,IAAI,mBACN,QACA,MACA,iBAAiB,QAAQ,QAAQ,OACpC;;;;;;;;;;;AAgCT,eAAsB,cAClB,MACA,UACwB;AACxB,KAAI;AACA,SAAO,WACD,MAAMA,WAAgB,KAAK,GAC3B,MAAMA,WAAgB,MAAM,OAAO;UACpC,OAAO;AACZ,QAAM,IAAI,mBACN,QACA,MACA,iBAAiB,QAAQ,QAAQ,OACpC"}
|
package/dist/run.d.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import { n as
|
|
1
|
+
import { n as CompressorOptions, r as MinifierOptions } from "./types-CWBFD3au.js";
|
|
2
2
|
|
|
3
3
|
//#region src/run.d.ts
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
6
|
+
* Execute the configured compressor and persist its outputs according to the provided settings.
|
|
7
7
|
*
|
|
8
|
-
* @param settings - Compressor settings including output targets and the `compressor` implementation
|
|
8
|
+
* @param settings - Compressor settings including output targets, options, and the `compressor` implementation
|
|
9
9
|
* @param content - The input content to be compressed
|
|
10
10
|
* @param index - Optional index used when processing multiple inputs
|
|
11
11
|
* @returns The minified code produced by the compressor
|
|
12
|
-
* @throws
|
|
12
|
+
* @throws ValidationError If `settings` is missing, `settings.compressor` is not provided, or the compressor returns an invalid result
|
|
13
13
|
*/
|
|
14
14
|
declare function run<T extends CompressorOptions = CompressorOptions>({
|
|
15
15
|
settings,
|
package/dist/run.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import { n as ValidationError } from "./error-
|
|
2
|
-
import {
|
|
1
|
+
import { n as ValidationError } from "./error-CUgKxOvI.js";
|
|
2
|
+
import { n as writeFileAsync } from "./writeFile-mfUS3rMz.js";
|
|
3
3
|
import { join, parse } from "node:path";
|
|
4
4
|
|
|
5
5
|
//#region src/run.ts
|
|
6
6
|
/*!
|
|
7
7
|
* node-minify
|
|
8
|
-
* Copyright(c) 2011-
|
|
8
|
+
* Copyright (c) 2011-2026 Rodolphe Stoclin
|
|
9
9
|
* MIT Licensed
|
|
10
10
|
*/
|
|
11
11
|
/**
|
|
12
|
-
*
|
|
12
|
+
* Execute the configured compressor and persist its outputs according to the provided settings.
|
|
13
13
|
*
|
|
14
|
-
* @param settings - Compressor settings including output targets and the `compressor` implementation
|
|
14
|
+
* @param settings - Compressor settings including output targets, options, and the `compressor` implementation
|
|
15
15
|
* @param content - The input content to be compressed
|
|
16
16
|
* @param index - Optional index used when processing multiple inputs
|
|
17
17
|
* @returns The minified code produced by the compressor
|
|
18
|
-
* @throws
|
|
18
|
+
* @throws ValidationError If `settings` is missing, `settings.compressor` is not provided, or the compressor returns an invalid result
|
|
19
19
|
*/
|
|
20
20
|
async function run({ settings, content, index }) {
|
|
21
21
|
if (!settings) throw new ValidationError("Settings must be provided");
|
|
@@ -25,45 +25,63 @@ async function run({ settings, content, index }) {
|
|
|
25
25
|
content,
|
|
26
26
|
index
|
|
27
27
|
});
|
|
28
|
-
|
|
28
|
+
validateCompressorResult(result, settings);
|
|
29
|
+
await writeOutput(result, settings, index);
|
|
29
30
|
return result.code;
|
|
30
31
|
}
|
|
31
32
|
/**
|
|
32
|
-
*
|
|
33
|
+
* Verify that a compressor result is an object containing a string `code` property and narrow its type to `CompressorResult`.
|
|
33
34
|
*
|
|
34
|
-
*
|
|
35
|
+
* @param result - The value returned by the compressor to validate.
|
|
36
|
+
* @param settings - Minifier settings (used to derive the compressor label for error messages).
|
|
37
|
+
* @throws ValidationError - If `result` is not an object with a string `code` property.
|
|
38
|
+
*/
|
|
39
|
+
function validateCompressorResult(result, settings) {
|
|
40
|
+
if (!result || typeof result !== "object") throw new ValidationError(`Compressor '${settings.compressorLabel || "compressor"}' returned invalid result. Expected an object with { code: string }.`);
|
|
41
|
+
const obj = result;
|
|
42
|
+
if (!("code" in obj) || typeof obj.code !== "string") throw new ValidationError(`Compressor '${settings.compressorLabel || "compressor"}' must return { code: string }. Got: ${JSON.stringify(Object.keys(obj))}`);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Write compressor outputs to configured output paths unless execution is in-memory.
|
|
35
46
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* @param
|
|
47
|
+
* Writes multiple outputs when `result.outputs` is present, writes `result.buffer` if provided, otherwise writes `result.code`. If `result.map` exists and a source map URL can be resolved from `settings`, the map file is written alongside the main output. The function returns without writing when `settings.output` is not set, when `settings.content` is provided (in-memory mode), or when `settings.allowEmptyOutput` is true and `result.code` is an empty string.
|
|
48
|
+
*
|
|
49
|
+
* @param result - Compressor result containing `code` and optional `buffer`, `map`, or `outputs`
|
|
50
|
+
* @param settings - Settings that determine output destinations and in-memory mode
|
|
51
|
+
* @param index - Optional batch/index marker forwarded to underlying write operations
|
|
39
52
|
*/
|
|
40
|
-
function writeOutput(result, settings, index) {
|
|
53
|
+
async function writeOutput(result, settings, index) {
|
|
41
54
|
if (Boolean(settings.content) || !settings.output) return;
|
|
55
|
+
const hasBuffer = result.buffer && result.buffer.length > 0;
|
|
56
|
+
const hasOutputs = result.outputs && result.outputs.length > 0;
|
|
57
|
+
const isCompletelyEmpty = !(result.code !== "") && !hasBuffer && !hasOutputs;
|
|
58
|
+
if (settings.allowEmptyOutput && isCompletelyEmpty) return;
|
|
42
59
|
if (result.outputs && result.outputs.length > 0) {
|
|
43
|
-
writeMultipleOutputs(result.outputs, settings, index);
|
|
60
|
+
await writeMultipleOutputs(result.outputs, settings, index);
|
|
44
61
|
return;
|
|
45
62
|
}
|
|
46
63
|
if (result.buffer) {
|
|
47
|
-
|
|
64
|
+
await writeFileAsync({
|
|
48
65
|
file: settings.output,
|
|
49
66
|
content: result.buffer,
|
|
50
67
|
index
|
|
51
68
|
});
|
|
52
69
|
return;
|
|
53
70
|
}
|
|
54
|
-
|
|
71
|
+
const writePromises = [writeFileAsync({
|
|
55
72
|
file: settings.output,
|
|
56
73
|
content: result.code,
|
|
57
74
|
index
|
|
58
|
-
});
|
|
75
|
+
})];
|
|
59
76
|
if (result.map) {
|
|
60
77
|
const sourceMapUrl = getSourceMapUrl(settings);
|
|
61
|
-
if (sourceMapUrl)
|
|
78
|
+
if (sourceMapUrl) writePromises.push(writeFileAsync({
|
|
62
79
|
file: sourceMapUrl,
|
|
63
80
|
content: result.map,
|
|
64
81
|
index
|
|
65
|
-
});
|
|
82
|
+
}));
|
|
66
83
|
}
|
|
84
|
+
await Promise.all(writePromises);
|
|
67
85
|
}
|
|
68
86
|
/**
|
|
69
87
|
* Extract the first input file path from the input configuration.
|
|
@@ -77,31 +95,23 @@ function getFirstInputFile(input) {
|
|
|
77
95
|
return "";
|
|
78
96
|
}
|
|
79
97
|
/**
|
|
80
|
-
* Write
|
|
81
|
-
*
|
|
82
|
-
* This writes each provided output entry to a computed target path:
|
|
83
|
-
* - If `settings.output` is an array, a non-empty array item (not "$1") at the same index is used verbatim as the target path.
|
|
84
|
-
* - If `settings.output` is the string "$1", the target is generated from the first input filename and the output's `format` (or "out" if missing).
|
|
85
|
-
* - If `settings.output` contains "$1", every "$1" is replaced with the input base name and the output's `format` is appended.
|
|
86
|
-
* - If `settings.output` is a plain string, that string is used with the output's `format` appended.
|
|
87
|
-
* - If no usable output pattern is provided, a default path is generated from the input filename and the output's `format`.
|
|
98
|
+
* Write compressor outputs to files resolved from the provided settings.
|
|
88
99
|
*
|
|
89
|
-
*
|
|
100
|
+
* Resolves a target path for each output entry based on settings.output and settings.input, then writes each entry's content to its resolved file location.
|
|
90
101
|
*
|
|
91
|
-
* @param outputs - Array of compressor
|
|
92
|
-
* @param settings - Settings used to resolve
|
|
93
|
-
* @param index - Optional index forwarded to the file writer
|
|
102
|
+
* @param outputs - Array of compressor output entries (each entry typically contains `content` and optional `format`) to be written.
|
|
103
|
+
* @param settings - Settings used to resolve target paths (may supply `output` pattern/array and `input` for deriving names).
|
|
104
|
+
* @param index - Optional numeric index forwarded to the file writer for each write operation.
|
|
94
105
|
*/
|
|
95
|
-
function writeMultipleOutputs(outputs, settings, index) {
|
|
106
|
+
async function writeMultipleOutputs(outputs, settings, index) {
|
|
96
107
|
const output = settings.output;
|
|
97
108
|
const isArrayOutput = Array.isArray(output);
|
|
98
109
|
const outputsArray = isArrayOutput ? output : [output];
|
|
99
110
|
const inputFile = getFirstInputFile(settings.input);
|
|
100
111
|
const inputDir = parse(inputFile).dir;
|
|
101
112
|
const inputBase = parse(inputFile).name;
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
if (!outputResult) continue;
|
|
113
|
+
const promises = outputs.map(async (outputResult, i) => {
|
|
114
|
+
if (!outputResult) return;
|
|
105
115
|
const format = outputResult.format || "out";
|
|
106
116
|
let targetFile;
|
|
107
117
|
const arrayItem = outputsArray[i];
|
|
@@ -117,12 +127,13 @@ function writeMultipleOutputs(outputs, settings, index) {
|
|
|
117
127
|
const baseName = inputBase || "output";
|
|
118
128
|
targetFile = inputDir ? join(inputDir, `${baseName}.${format}`) : `${baseName}.${format}`;
|
|
119
129
|
}
|
|
120
|
-
|
|
130
|
+
await writeFileAsync({
|
|
121
131
|
file: targetFile,
|
|
122
132
|
content: outputResult.content,
|
|
123
133
|
index
|
|
124
134
|
});
|
|
125
|
-
}
|
|
135
|
+
});
|
|
136
|
+
await Promise.all(promises);
|
|
126
137
|
}
|
|
127
138
|
/**
|
|
128
139
|
* Resolve the configured source map path or URL from the provided settings.
|
package/dist/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.js","names":["targetFile: string"],"sources":["../src/run.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport { join, parse } from \"node:path\";\nimport type {\n CompressorOptions,\n CompressorResult,\n MinifierOptions,\n Settings,\n} from \"@node-minify/types\";\nimport { ValidationError } from \"./error.ts\";\nimport { writeFile } from \"./writeFile.ts\";\n\n/**\n * Run the configured compressor and persist its outputs according to the provided settings.\n *\n * @param settings - Compressor settings including output targets and the `compressor` implementation\n * @param content - The input content to be compressed\n * @param index - Optional index used when processing multiple inputs\n * @returns The minified code produced by the compressor\n * @throws {ValidationError} If `settings` is missing or `settings.compressor` is not provided\n */\nexport async function run<T extends CompressorOptions = CompressorOptions>({\n settings,\n content,\n index,\n}: MinifierOptions<T>): Promise<string> {\n if (!settings) {\n throw new ValidationError(\"Settings must be provided\");\n }\n\n if (!settings.compressor) {\n throw new ValidationError(\"Compressor must be provided in settings\");\n }\n\n const result = await settings.compressor({\n settings,\n content,\n index,\n });\n\n writeOutput(result, settings, index);\n\n return result.code;\n}\n\n/**\n * Write compressor result outputs to disk unless the operation is in-memory.\n *\n * Writes multiple output files when `result.outputs` is provided, writes a binary `result.buffer` to the configured output when present, otherwise writes `result.code`. If a source map is available and a source map URL can be resolved from `settings`, the map is written alongside the main output.\n *\n * @param result - The compressor result containing `code`, optional `buffer`, `map`, or `outputs` describing one or more outputs\n * @param settings - Settings that include output destination(s) and optional in-memory `content` which disables disk writes\n * @param index - Optional index used when writing to multiple targets or when tracking a particular input within a batch\n */\nfunction writeOutput<T extends CompressorOptions = CompressorOptions>(\n result: CompressorResult,\n settings: Settings<T>,\n index?: number\n): void {\n const isInMemoryMode = Boolean(settings.content);\n if (isInMemoryMode || !settings.output) {\n return;\n }\n\n // Handle multi-output (for image conversion to multiple formats)\n if (result.outputs && result.outputs.length > 0) {\n writeMultipleOutputs(result.outputs, settings, index);\n return;\n }\n\n // Handle single buffer output (for binary images)\n if (result.buffer) {\n writeFile({ file: settings.output, content: result.buffer, index });\n return;\n }\n\n // Default: write code (string) output\n writeFile({ file: settings.output, content: result.code, index });\n\n if (result.map) {\n const sourceMapUrl = getSourceMapUrl(settings);\n if (sourceMapUrl) {\n writeFile({ file: sourceMapUrl, content: result.map, index });\n }\n }\n}\n\n/**\n * Extract the first input file path from the input configuration.\n *\n * @param input - A single file path, an array of paths, or undefined\n * @returns The first input file path, or an empty string if none available\n */\nfunction getFirstInputFile(input: string | string[] | undefined): string {\n if (typeof input === \"string\") {\n return input;\n }\n if (Array.isArray(input) && input.length > 0) {\n return input[0] ?? \"\";\n }\n return \"\";\n}\n\n/**\n * Write multiple output files produced by a compressor according to the settings' output configuration.\n *\n * This writes each provided output entry to a computed target path:\n * - If `settings.output` is an array, a non-empty array item (not \"$1\") at the same index is used verbatim as the target path.\n * - If `settings.output` is the string \"$1\", the target is generated from the first input filename and the output's `format` (or \"out\" if missing).\n * - If `settings.output` contains \"$1\", every \"$1\" is replaced with the input base name and the output's `format` is appended.\n * - If `settings.output` is a plain string, that string is used with the output's `format` appended.\n * - If no usable output pattern is provided, a default path is generated from the input filename and the output's `format`.\n *\n * Each output's `content` is written to its resolved path using `writeFile`. The first input (if any) is used to derive base names and directories for auto-generated targets.\n *\n * @param outputs - Array of compressor outputs (each may include `content` and optional `format`) to write.\n * @param settings - Settings used to resolve output targets (may supply `output` and `input`).\n * @param index - Optional index forwarded to the file writer when writing each output.\n */\nfunction writeMultipleOutputs<T extends CompressorOptions = CompressorOptions>(\n outputs: NonNullable<CompressorResult[\"outputs\"]>,\n settings: Settings<T>,\n index?: number\n): void {\n const output = settings.output;\n const isArrayOutput = Array.isArray(output);\n const outputsArray = isArrayOutput ? output : [output];\n const inputFile = getFirstInputFile(settings.input);\n const inputDir = parse(inputFile).dir;\n const inputBase = parse(inputFile).name;\n\n for (let i = 0; i < outputs.length; i++) {\n const outputResult = outputs[i];\n if (!outputResult) {\n continue;\n }\n\n const format = outputResult.format || \"out\";\n let targetFile: string;\n\n const arrayItem = outputsArray[i];\n\n if (\n isArrayOutput &&\n arrayItem !== undefined &&\n arrayItem !== \"$1\" &&\n arrayItem.trim() !== \"\"\n ) {\n // Explicit output path provided in array - use as-is\n targetFile = arrayItem;\n } else if (typeof output === \"string\" && output === \"$1\") {\n // $1 only: auto-generate from input filename in input directory\n const baseName = inputBase || \"output\";\n targetFile = inputDir\n ? join(inputDir, `${baseName}.${format}`)\n : `${baseName}.${format}`;\n } else if (typeof output === \"string\" && output.includes(\"$1\")) {\n // $1 pattern in path: replace and append format\n const extensionlessName = inputBase || \"output\";\n const outputFile = output.replace(/\\$1/g, extensionlessName);\n targetFile = `${outputFile}.${format}`;\n } else if (typeof output === \"string\") {\n // Single string output: append format extension\n targetFile = `${output}.${format}`;\n } else {\n // Fallback\n const baseName = inputBase || \"output\";\n targetFile = inputDir\n ? join(inputDir, `${baseName}.${format}`)\n : `${baseName}.${format}`;\n }\n\n writeFile({ file: targetFile, content: outputResult.content, index });\n }\n}\n\n/**\n * Resolve the configured source map path or URL from the provided settings.\n *\n * @param settings - Minifier settings that may include `options.sourceMap` or `options._sourceMap`\n * @returns The source map URL or filename when configured, `undefined` otherwise.\n */\nfunction getSourceMapUrl<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): string | undefined {\n const options = settings.options as Record<string, unknown> | undefined;\n if (!options) {\n return undefined;\n }\n\n const sourceMap = options.sourceMap as Record<string, unknown> | undefined;\n if (sourceMap) {\n if (typeof sourceMap.url === \"string\") {\n return sourceMap.url;\n }\n if (typeof sourceMap.filename === \"string\") {\n return sourceMap.filename;\n }\n }\n\n const _sourceMap = options._sourceMap as\n | Record<string, unknown>\n | undefined;\n if (_sourceMap && typeof _sourceMap.url === \"string\") {\n return _sourceMap.url;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,eAAsB,IAAqD,EACvE,UACA,SACA,SACoC;AACpC,KAAI,CAAC,SACD,OAAM,IAAI,gBAAgB,4BAA4B;AAG1D,KAAI,CAAC,SAAS,WACV,OAAM,IAAI,gBAAgB,0CAA0C;CAGxE,MAAM,SAAS,MAAM,SAAS,WAAW;EACrC;EACA;EACA;EACH,CAAC;AAEF,aAAY,QAAQ,UAAU,MAAM;AAEpC,QAAO,OAAO;;;;;;;;;;;AAYlB,SAAS,YACL,QACA,UACA,OACI;AAEJ,KADuB,QAAQ,SAAS,QAAQ,IAC1B,CAAC,SAAS,OAC5B;AAIJ,KAAI,OAAO,WAAW,OAAO,QAAQ,SAAS,GAAG;AAC7C,uBAAqB,OAAO,SAAS,UAAU,MAAM;AACrD;;AAIJ,KAAI,OAAO,QAAQ;AACf,YAAU;GAAE,MAAM,SAAS;GAAQ,SAAS,OAAO;GAAQ;GAAO,CAAC;AACnE;;AAIJ,WAAU;EAAE,MAAM,SAAS;EAAQ,SAAS,OAAO;EAAM;EAAO,CAAC;AAEjE,KAAI,OAAO,KAAK;EACZ,MAAM,eAAe,gBAAgB,SAAS;AAC9C,MAAI,aACA,WAAU;GAAE,MAAM;GAAc,SAAS,OAAO;GAAK;GAAO,CAAC;;;;;;;;;AAWzE,SAAS,kBAAkB,OAA8C;AACrE,KAAI,OAAO,UAAU,SACjB,QAAO;AAEX,KAAI,MAAM,QAAQ,MAAM,IAAI,MAAM,SAAS,EACvC,QAAO,MAAM,MAAM;AAEvB,QAAO;;;;;;;;;;;;;;;;;;AAmBX,SAAS,qBACL,SACA,UACA,OACI;CACJ,MAAM,SAAS,SAAS;CACxB,MAAM,gBAAgB,MAAM,QAAQ,OAAO;CAC3C,MAAM,eAAe,gBAAgB,SAAS,CAAC,OAAO;CACtD,MAAM,YAAY,kBAAkB,SAAS,MAAM;CACnD,MAAM,WAAW,MAAM,UAAU,CAAC;CAClC,MAAM,YAAY,MAAM,UAAU,CAAC;AAEnC,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACrC,MAAM,eAAe,QAAQ;AAC7B,MAAI,CAAC,aACD;EAGJ,MAAM,SAAS,aAAa,UAAU;EACtC,IAAIA;EAEJ,MAAM,YAAY,aAAa;AAE/B,MACI,iBACA,cAAc,UACd,cAAc,QACd,UAAU,MAAM,KAAK,GAGrB,cAAa;WACN,OAAO,WAAW,YAAY,WAAW,MAAM;GAEtD,MAAM,WAAW,aAAa;AAC9B,gBAAa,WACP,KAAK,UAAU,GAAG,SAAS,GAAG,SAAS,GACvC,GAAG,SAAS,GAAG;aACd,OAAO,WAAW,YAAY,OAAO,SAAS,KAAK,EAAE;GAE5D,MAAM,oBAAoB,aAAa;AAEvC,gBAAa,GADM,OAAO,QAAQ,QAAQ,kBAAkB,CACjC,GAAG;aACvB,OAAO,WAAW,SAEzB,cAAa,GAAG,OAAO,GAAG;OACvB;GAEH,MAAM,WAAW,aAAa;AAC9B,gBAAa,WACP,KAAK,UAAU,GAAG,SAAS,GAAG,SAAS,GACvC,GAAG,SAAS,GAAG;;AAGzB,YAAU;GAAE,MAAM;GAAY,SAAS,aAAa;GAAS;GAAO,CAAC;;;;;;;;;AAU7E,SAAS,gBACL,UACkB;CAClB,MAAM,UAAU,SAAS;AACzB,KAAI,CAAC,QACD;CAGJ,MAAM,YAAY,QAAQ;AAC1B,KAAI,WAAW;AACX,MAAI,OAAO,UAAU,QAAQ,SACzB,QAAO,UAAU;AAErB,MAAI,OAAO,UAAU,aAAa,SAC9B,QAAO,UAAU;;CAIzB,MAAM,aAAa,QAAQ;AAG3B,KAAI,cAAc,OAAO,WAAW,QAAQ,SACxC,QAAO,WAAW"}
|
|
1
|
+
{"version":3,"file":"run.js","names":[],"sources":["../src/run.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport { join, parse } from \"node:path\";\nimport type {\n CompressorOptions,\n CompressorResult,\n MinifierOptions,\n Settings,\n} from \"@node-minify/types\";\nimport { ValidationError } from \"./error.ts\";\nimport { writeFileAsync } from \"./writeFile.ts\";\n\n/**\n * Execute the configured compressor and persist its outputs according to the provided settings.\n *\n * @param settings - Compressor settings including output targets, options, and the `compressor` implementation\n * @param content - The input content to be compressed\n * @param index - Optional index used when processing multiple inputs\n * @returns The minified code produced by the compressor\n * @throws ValidationError If `settings` is missing, `settings.compressor` is not provided, or the compressor returns an invalid result\n */\nexport async function run<T extends CompressorOptions = CompressorOptions>({\n settings,\n content,\n index,\n}: MinifierOptions<T>): Promise<string> {\n if (!settings) {\n throw new ValidationError(\"Settings must be provided\");\n }\n\n if (!settings.compressor) {\n throw new ValidationError(\"Compressor must be provided in settings\");\n }\n\n const result = await settings.compressor({\n settings,\n content,\n index,\n });\n\n validateCompressorResult(result, settings);\n\n await writeOutput(result, settings, index);\n\n return result.code;\n}\n\n/**\n * Verify that a compressor result is an object containing a string `code` property and narrow its type to `CompressorResult`.\n *\n * @param result - The value returned by the compressor to validate.\n * @param settings - Minifier settings (used to derive the compressor label for error messages).\n * @throws ValidationError - If `result` is not an object with a string `code` property.\n */\nfunction validateCompressorResult<\n T extends CompressorOptions = CompressorOptions,\n>(result: unknown, settings: Settings<T>): asserts result is CompressorResult {\n if (!result || typeof result !== \"object\") {\n const label = settings.compressorLabel || \"compressor\";\n throw new ValidationError(\n `Compressor '${label}' returned invalid result. Expected an object with { code: string }.`\n );\n }\n\n const obj = result as Record<string, unknown>;\n if (!(\"code\" in obj) || typeof obj.code !== \"string\") {\n const label = settings.compressorLabel || \"compressor\";\n throw new ValidationError(\n `Compressor '${label}' must return { code: string }. Got: ${JSON.stringify(Object.keys(obj))}`\n );\n }\n}\n\n/**\n * Write compressor outputs to configured output paths unless execution is in-memory.\n *\n * Writes multiple outputs when `result.outputs` is present, writes `result.buffer` if provided, otherwise writes `result.code`. If `result.map` exists and a source map URL can be resolved from `settings`, the map file is written alongside the main output. The function returns without writing when `settings.output` is not set, when `settings.content` is provided (in-memory mode), or when `settings.allowEmptyOutput` is true and `result.code` is an empty string.\n *\n * @param result - Compressor result containing `code` and optional `buffer`, `map`, or `outputs`\n * @param settings - Settings that determine output destinations and in-memory mode\n * @param index - Optional batch/index marker forwarded to underlying write operations\n */\nasync function writeOutput<T extends CompressorOptions = CompressorOptions>(\n result: CompressorResult,\n settings: Settings<T>,\n index?: number\n): Promise<void> {\n const isInMemoryMode = Boolean(settings.content);\n if (isInMemoryMode || !settings.output) {\n return;\n }\n\n const hasBuffer = result.buffer && result.buffer.length > 0;\n const hasOutputs = result.outputs && result.outputs.length > 0;\n const hasCode = result.code !== \"\";\n const isCompletelyEmpty = !hasCode && !hasBuffer && !hasOutputs;\n if (settings.allowEmptyOutput && isCompletelyEmpty) {\n return;\n }\n\n // Handle multi-output (for image conversion to multiple formats)\n if (result.outputs && result.outputs.length > 0) {\n await writeMultipleOutputs(result.outputs, settings, index);\n return;\n }\n\n // Handle single buffer output (for binary images)\n if (result.buffer) {\n await writeFileAsync({\n file: settings.output,\n content: result.buffer,\n index,\n });\n return;\n }\n\n // Default: write code (string) output\n const writePromises = [\n writeFileAsync({\n file: settings.output,\n content: result.code,\n index,\n }),\n ];\n\n if (result.map) {\n const sourceMapUrl = getSourceMapUrl(settings);\n if (sourceMapUrl) {\n writePromises.push(\n writeFileAsync({\n file: sourceMapUrl,\n content: result.map,\n index,\n })\n );\n }\n }\n\n await Promise.all(writePromises);\n}\n\n/**\n * Extract the first input file path from the input configuration.\n *\n * @param input - A single file path, an array of paths, or undefined\n * @returns The first input file path, or an empty string if none available\n */\nfunction getFirstInputFile(input: string | string[] | undefined): string {\n if (typeof input === \"string\") {\n return input;\n }\n if (Array.isArray(input) && input.length > 0) {\n return input[0] ?? \"\";\n }\n return \"\";\n}\n\n/**\n * Write compressor outputs to files resolved from the provided settings.\n *\n * Resolves a target path for each output entry based on settings.output and settings.input, then writes each entry's content to its resolved file location.\n *\n * @param outputs - Array of compressor output entries (each entry typically contains `content` and optional `format`) to be written.\n * @param settings - Settings used to resolve target paths (may supply `output` pattern/array and `input` for deriving names).\n * @param index - Optional numeric index forwarded to the file writer for each write operation.\n */\nasync function writeMultipleOutputs<\n T extends CompressorOptions = CompressorOptions,\n>(\n outputs: NonNullable<CompressorResult[\"outputs\"]>,\n settings: Settings<T>,\n index?: number\n): Promise<void> {\n const output = settings.output;\n const isArrayOutput = Array.isArray(output);\n const outputsArray = isArrayOutput ? output : [output];\n const inputFile = getFirstInputFile(settings.input);\n const inputDir = parse(inputFile).dir;\n const inputBase = parse(inputFile).name;\n\n const promises = outputs.map(async (outputResult, i) => {\n if (!outputResult) {\n return;\n }\n\n // Write outputs in parallel to improve performance\n const format = outputResult.format || \"out\";\n let targetFile: string;\n\n const arrayItem = outputsArray[i];\n\n if (\n isArrayOutput &&\n arrayItem !== undefined &&\n arrayItem !== \"$1\" &&\n arrayItem.trim() !== \"\"\n ) {\n // Explicit output path provided in array - use as-is\n targetFile = arrayItem;\n } else if (typeof output === \"string\" && output === \"$1\") {\n // $1 only: auto-generate from input filename in input directory\n const baseName = inputBase || \"output\";\n targetFile = inputDir\n ? join(inputDir, `${baseName}.${format}`)\n : `${baseName}.${format}`;\n } else if (typeof output === \"string\" && output.includes(\"$1\")) {\n // $1 pattern in path: replace and append format\n const extensionlessName = inputBase || \"output\";\n const outputFile = output.replace(/\\$1/g, extensionlessName);\n targetFile = `${outputFile}.${format}`;\n } else if (typeof output === \"string\") {\n // Single string output: append format extension\n targetFile = `${output}.${format}`;\n } else {\n // Fallback\n const baseName = inputBase || \"output\";\n targetFile = inputDir\n ? join(inputDir, `${baseName}.${format}`)\n : `${baseName}.${format}`;\n }\n\n await writeFileAsync({\n file: targetFile,\n content: outputResult.content,\n index,\n });\n });\n\n await Promise.all(promises);\n}\n\n/**\n * Resolve the configured source map path or URL from the provided settings.\n *\n * @param settings - Minifier settings that may include `options.sourceMap` or `options._sourceMap`\n * @returns The source map URL or filename when configured, `undefined` otherwise.\n */\nfunction getSourceMapUrl<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): string | undefined {\n const options = settings.options as Record<string, unknown> | undefined;\n if (!options) {\n return undefined;\n }\n\n const sourceMap = options.sourceMap as Record<string, unknown> | undefined;\n if (sourceMap) {\n if (typeof sourceMap.url === \"string\") {\n return sourceMap.url;\n }\n if (typeof sourceMap.filename === \"string\") {\n return sourceMap.filename;\n }\n }\n\n const _sourceMap = options._sourceMap as\n | Record<string, unknown>\n | undefined;\n if (_sourceMap && typeof _sourceMap.url === \"string\") {\n return _sourceMap.url;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,eAAsB,IAAqD,EACvE,UACA,SACA,SACoC;AACpC,KAAI,CAAC,SACD,OAAM,IAAI,gBAAgB,4BAA4B;AAG1D,KAAI,CAAC,SAAS,WACV,OAAM,IAAI,gBAAgB,0CAA0C;CAGxE,MAAM,SAAS,MAAM,SAAS,WAAW;EACrC;EACA;EACA;EACH,CAAC;AAEF,0BAAyB,QAAQ,SAAS;AAE1C,OAAM,YAAY,QAAQ,UAAU,MAAM;AAE1C,QAAO,OAAO;;;;;;;;;AAUlB,SAAS,yBAEP,QAAiB,UAA2D;AAC1E,KAAI,CAAC,UAAU,OAAO,WAAW,SAE7B,OAAM,IAAI,gBACN,eAFU,SAAS,mBAAmB,aAEjB,sEACxB;CAGL,MAAM,MAAM;AACZ,KAAI,EAAE,UAAU,QAAQ,OAAO,IAAI,SAAS,SAExC,OAAM,IAAI,gBACN,eAFU,SAAS,mBAAmB,aAEjB,uCAAuC,KAAK,UAAU,OAAO,KAAK,IAAI,CAAC,GAC/F;;;;;;;;;;;AAaT,eAAe,YACX,QACA,UACA,OACa;AAEb,KADuB,QAAQ,SAAS,QAAQ,IAC1B,CAAC,SAAS,OAC5B;CAGJ,MAAM,YAAY,OAAO,UAAU,OAAO,OAAO,SAAS;CAC1D,MAAM,aAAa,OAAO,WAAW,OAAO,QAAQ,SAAS;CAE7D,MAAM,oBAAoB,EADV,OAAO,SAAS,OACM,CAAC,aAAa,CAAC;AACrD,KAAI,SAAS,oBAAoB,kBAC7B;AAIJ,KAAI,OAAO,WAAW,OAAO,QAAQ,SAAS,GAAG;AAC7C,QAAM,qBAAqB,OAAO,SAAS,UAAU,MAAM;AAC3D;;AAIJ,KAAI,OAAO,QAAQ;AACf,QAAM,eAAe;GACjB,MAAM,SAAS;GACf,SAAS,OAAO;GAChB;GACH,CAAC;AACF;;CAIJ,MAAM,gBAAgB,CAClB,eAAe;EACX,MAAM,SAAS;EACf,SAAS,OAAO;EAChB;EACH,CAAC,CACL;AAED,KAAI,OAAO,KAAK;EACZ,MAAM,eAAe,gBAAgB,SAAS;AAC9C,MAAI,aACA,eAAc,KACV,eAAe;GACX,MAAM;GACN,SAAS,OAAO;GAChB;GACH,CAAC,CACL;;AAIT,OAAM,QAAQ,IAAI,cAAc;;;;;;;;AASpC,SAAS,kBAAkB,OAA8C;AACrE,KAAI,OAAO,UAAU,SACjB,QAAO;AAEX,KAAI,MAAM,QAAQ,MAAM,IAAI,MAAM,SAAS,EACvC,QAAO,MAAM,MAAM;AAEvB,QAAO;;;;;;;;;;;AAYX,eAAe,qBAGX,SACA,UACA,OACa;CACb,MAAM,SAAS,SAAS;CACxB,MAAM,gBAAgB,MAAM,QAAQ,OAAO;CAC3C,MAAM,eAAe,gBAAgB,SAAS,CAAC,OAAO;CACtD,MAAM,YAAY,kBAAkB,SAAS,MAAM;CACnD,MAAM,WAAW,MAAM,UAAU,CAAC;CAClC,MAAM,YAAY,MAAM,UAAU,CAAC;CAEnC,MAAM,WAAW,QAAQ,IAAI,OAAO,cAAc,MAAM;AACpD,MAAI,CAAC,aACD;EAIJ,MAAM,SAAS,aAAa,UAAU;EACtC,IAAI;EAEJ,MAAM,YAAY,aAAa;AAE/B,MACI,iBACA,cAAc,UACd,cAAc,QACd,UAAU,MAAM,KAAK,GAGrB,cAAa;WACN,OAAO,WAAW,YAAY,WAAW,MAAM;GAEtD,MAAM,WAAW,aAAa;AAC9B,gBAAa,WACP,KAAK,UAAU,GAAG,SAAS,GAAG,SAAS,GACvC,GAAG,SAAS,GAAG;aACd,OAAO,WAAW,YAAY,OAAO,SAAS,KAAK,EAAE;GAE5D,MAAM,oBAAoB,aAAa;AAEvC,gBAAa,GADM,OAAO,QAAQ,QAAQ,kBAAkB,CACjC,GAAG;aACvB,OAAO,WAAW,SAEzB,cAAa,GAAG,OAAO,GAAG;OACvB;GAEH,MAAM,WAAW,aAAa;AAC9B,gBAAa,WACP,KAAK,UAAU,GAAG,SAAS,GAAG,SAAS,GACvC,GAAG,SAAS,GAAG;;AAGzB,QAAM,eAAe;GACjB,MAAM;GACN,SAAS,aAAa;GACtB;GACH,CAAC;GACJ;AAEF,OAAM,QAAQ,IAAI,SAAS;;;;;;;;AAS/B,SAAS,gBACL,UACkB;CAClB,MAAM,UAAU,SAAS;AACzB,KAAI,CAAC,QACD;CAGJ,MAAM,YAAY,QAAQ;AAC1B,KAAI,WAAW;AACX,MAAI,OAAO,UAAU,QAAQ,SACzB,QAAO,UAAU;AAErB,MAAI,OAAO,UAAU,aAAa,SAC9B,QAAO,UAAU;;CAIzB,MAAM,aAAa,QAAQ;AAG3B,KAAI,cAAc,OAAO,WAAW,QAAQ,SACxC,QAAO,WAAW"}
|
package/dist/setFileNameMin.d.ts
CHANGED
package/dist/setFileNameMin.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { n as ValidationError } from "./error-
|
|
1
|
+
import { n as ValidationError } from "./error-CUgKxOvI.js";
|
|
2
2
|
|
|
3
3
|
//#region src/setFileNameMin.ts
|
|
4
4
|
/*!
|
|
5
5
|
* node-minify
|
|
6
|
-
* Copyright(c) 2011-
|
|
6
|
+
* Copyright (c) 2011-2026 Rodolphe Stoclin
|
|
7
7
|
* MIT Licensed
|
|
8
8
|
*/
|
|
9
9
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setFileNameMin.js","names":[],"sources":["../src/setFileNameMin.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-
|
|
1
|
+
{"version":3,"file":"setFileNameMin.js","names":[],"sources":["../src/setFileNameMin.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport { ValidationError } from \"./error.ts\";\n\n/**\n * Set the file name as minified.\n * @param file Original file path\n * @param output Output pattern (use $1 as placeholder for filename)\n * @param publicFolder Optional public folder prefix\n * @param replaceInPlace Whether to keep original path\n * @returns Minified file path\n * @throws {ValidationError} If input parameters are invalid\n * @example\n * setFileNameMin('src/file.js', '$1.min.js') // 'src/file.min.js'\n * setFileNameMin('file.js', '$1.min.js', 'public/') // 'public/file.min.js'\n */\nexport function setFileNameMin(\n file: string,\n output: string,\n publicFolder?: string,\n replaceInPlace?: boolean\n): string {\n if (!file || typeof file !== \"string\") {\n throw new ValidationError(\"File path must be a non-empty string\");\n }\n\n if (!output || typeof output !== \"string\" || !output.includes(\"$1\")) {\n throw new ValidationError(\n 'Output pattern must be a string containing \"$1\"'\n );\n }\n\n try {\n const lastSlashIndex = file.lastIndexOf(\"/\");\n const filePath = file.substring(0, lastSlashIndex + 1);\n const fileWithoutPath = file.substring(lastSlashIndex + 1);\n const lastDotIndex = fileWithoutPath.lastIndexOf(\".\");\n\n if (lastDotIndex === -1) {\n throw new ValidationError(\"File must have an extension\");\n }\n\n let fileWithoutExtension = fileWithoutPath.substring(0, lastDotIndex);\n\n if (publicFolder) {\n if (typeof publicFolder !== \"string\") {\n throw new ValidationError(\"Public folder must be a string\");\n }\n fileWithoutExtension = publicFolder + fileWithoutExtension;\n }\n\n if (replaceInPlace) {\n fileWithoutExtension = filePath + fileWithoutExtension;\n }\n\n return output.replace(\"$1\", fileWithoutExtension);\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ValidationError(\n `Failed to process file name: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,eACZ,MACA,QACA,cACA,gBACM;AACN,KAAI,CAAC,QAAQ,OAAO,SAAS,SACzB,OAAM,IAAI,gBAAgB,uCAAuC;AAGrE,KAAI,CAAC,UAAU,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,KAAK,CAC/D,OAAM,IAAI,gBACN,oDACH;AAGL,KAAI;EACA,MAAM,iBAAiB,KAAK,YAAY,IAAI;EAC5C,MAAM,WAAW,KAAK,UAAU,GAAG,iBAAiB,EAAE;EACtD,MAAM,kBAAkB,KAAK,UAAU,iBAAiB,EAAE;EAC1D,MAAM,eAAe,gBAAgB,YAAY,IAAI;AAErD,MAAI,iBAAiB,GACjB,OAAM,IAAI,gBAAgB,8BAA8B;EAG5D,IAAI,uBAAuB,gBAAgB,UAAU,GAAG,aAAa;AAErE,MAAI,cAAc;AACd,OAAI,OAAO,iBAAiB,SACxB,OAAM,IAAI,gBAAgB,iCAAiC;AAE/D,0BAAuB,eAAe;;AAG1C,MAAI,eACA,wBAAuB,WAAW;AAGtC,SAAO,OAAO,QAAQ,MAAM,qBAAqB;UAC5C,OAAO;AACZ,MAAI,iBAAiB,gBACjB,OAAM;AAEV,QAAM,IAAI,gBACN,gCAAgC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GACzF"}
|
package/dist/setPublicFolder.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setPublicFolder.js","names":[],"sources":["../src/setPublicFolder.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-
|
|
1
|
+
{"version":3,"file":"setPublicFolder.js","names":[],"sources":["../src/setPublicFolder.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport path from \"node:path\";\n\n/**\n * Prepend the public folder to each file.\n * @param input Path to file(s)\n * @param publicFolder Path to the public folder\n */\nexport function setPublicFolder(\n input: string | string[],\n publicFolder: string\n) {\n if (typeof publicFolder !== \"string\") {\n return {};\n }\n\n const normalizedPublicFolder = path.normalize(publicFolder);\n\n const addPublicFolder = (item: string) => {\n const normalizedPath = path.normalize(item);\n return normalizedPath.includes(normalizedPublicFolder)\n ? normalizedPath\n : path.normalize(normalizedPublicFolder + item);\n };\n\n return {\n input: Array.isArray(input)\n ? input.map(addPublicFolder)\n : addPublicFolder(input),\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,gBACZ,OACA,cACF;AACE,KAAI,OAAO,iBAAiB,SACxB,QAAO,EAAE;CAGb,MAAM,yBAAyB,KAAK,UAAU,aAAa;CAE3D,MAAM,mBAAmB,SAAiB;EACtC,MAAM,iBAAiB,KAAK,UAAU,KAAK;AAC3C,SAAO,eAAe,SAAS,uBAAuB,GAChD,iBACA,KAAK,UAAU,yBAAyB,KAAK;;AAGvD,QAAO,EACH,OAAO,MAAM,QAAQ,MAAM,GACrB,MAAM,IAAI,gBAAgB,GAC1B,gBAAgB,MAAM,EAC/B"}
|
|
@@ -135,6 +135,12 @@ type Settings<TOptions extends CompressorOptions = CompressorOptions> = {
|
|
|
135
135
|
*/
|
|
136
136
|
buffer?: number;
|
|
137
137
|
|
|
138
|
+
/**
|
|
139
|
+
* Timeout for the compressor process (in milliseconds).
|
|
140
|
+
* If execution exceeds this limit, the process will be killed.
|
|
141
|
+
*/
|
|
142
|
+
timeout?: number;
|
|
143
|
+
|
|
138
144
|
/**
|
|
139
145
|
* File type for compressors that support multiple types.
|
|
140
146
|
* Required for YUI compressor.
|
|
@@ -161,6 +167,14 @@ type Settings<TOptions extends CompressorOptions = CompressorOptions> = {
|
|
|
161
167
|
* @default false
|
|
162
168
|
*/
|
|
163
169
|
replaceInPlace?: boolean;
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Allow empty output without throwing an error.
|
|
173
|
+
* When true, if minification results in empty content, the output file will not be written.
|
|
174
|
+
* Useful for CSS files containing only comments that get stripped.
|
|
175
|
+
* @default false
|
|
176
|
+
*/
|
|
177
|
+
allowEmptyOutput?: boolean;
|
|
164
178
|
};
|
|
165
179
|
/**
|
|
166
180
|
* Options passed to compressor functions internally.
|
|
@@ -186,5 +200,5 @@ type MinifierOptions<TOptions extends CompressorOptions = CompressorOptions> = {
|
|
|
186
200
|
index?: number;
|
|
187
201
|
};
|
|
188
202
|
//#endregion
|
|
189
|
-
export {
|
|
190
|
-
//# sourceMappingURL=types-
|
|
203
|
+
export { Settings as i, CompressorOptions as n, MinifierOptions as r, Compressor as t };
|
|
204
|
+
//# sourceMappingURL=types-CWBFD3au.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-CWBFD3au.d.ts","names":["CompressorReturnType","ImageFormat","CompressorOutput","Buffer","CompressorResult","CompressorOptions","Record","Compressor","TOptions","MinifierOptions","Promise","FileType","Settings","Result","MinifyOptions"],"sources":["../../types/src/types.d.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * The return type of a compressor function.\n * @deprecated Use `CompressorResult` instead. Will be removed in v11.\n */\nexport type CompressorReturnType = string;\n\n/**\n * Supported image formats for image compression.\n */\nexport type ImageFormat =\n | \"webp\"\n | \"avif\"\n | \"png\"\n | \"jpeg\"\n | \"jpg\"\n | \"gif\"\n | \"tiff\"\n | \"heif\"\n | \"heic\";\n\n/**\n * Output result for multi-format image compression.\n */\nexport type CompressorOutput = {\n /**\n * Format of the output (e.g., 'webp', 'avif').\n */\n format?: string;\n\n /**\n * Output content as string or Buffer.\n */\n content: string | Buffer;\n};\n\n/**\n * Result returned by a compressor function.\n */\nexport type CompressorResult = {\n /**\n * Minified content as string (for text-based formats like JS, CSS, HTML, SVG).\n */\n code: string;\n\n /**\n * Source map (for JS/CSS compressors).\n */\n map?: string;\n\n /**\n * Minified content as Buffer (for binary formats like images).\n * @example\n * When using sharp for PNG/WebP compression\n */\n buffer?: Buffer;\n\n /**\n * Multiple outputs for multi-format image compression.\n * Used when converting to multiple formats simultaneously.\n * @example\n * [{ format: 'webp', content: <Buffer> }, { format: 'avif', content: <Buffer> }]\n */\n outputs?: CompressorOutput[];\n};\n\n/**\n * Base options that all compressors can accept.\n * Specific compressors may extend this with their own options.\n */\nexport type CompressorOptions = Record<string, unknown>;\n\n/**\n * A compressor function that minifies content.\n * @param args - The minifier options including settings and content\n * @returns A promise resolving to the compression result\n */\nexport type Compressor<TOptions extends CompressorOptions = CompressorOptions> =\n (args: MinifierOptions<TOptions>) => Promise<CompressorResult>;\n\n/**\n * File type for compressors that support multiple types (e.g., YUI).\n */\nexport type FileType = \"js\" | \"css\";\n\n/**\n * User-facing settings for the minify function.\n * This is what users pass when calling minify().\n *\n * @example\n * ```ts\n * import { minify } from '@node-minify/core';\n * import { terser } from '@node-minify/terser';\n *\n * await minify({\n * compressor: terser,\n * input: 'src/*.js',\n * output: 'dist/bundle.min.js',\n * options: { mangle: true }\n * });\n * ```\n */\nexport type Settings<TOptions extends CompressorOptions = CompressorOptions> = {\n /**\n * The compressor function to use for minification.\n */\n compressor: Compressor<TOptions>;\n\n /**\n * Optional label for the compressor (used in logging).\n */\n compressorLabel?: string;\n\n /**\n * Content to minify (for in-memory minification).\n * If provided, input/output are not required.\n * For text-based formats (JS, CSS, HTML, SVG): string\n * For binary formats (images): Buffer (handled internally by image compressors)\n */\n content?: string | Buffer;\n\n /**\n * Input file path(s) or glob pattern.\n * Can be a single file, array of files, or wildcard pattern.\n *\n * @example\n * - 'src/app.js'\n * - ['src/a.js', 'src/b.js']\n * - 'src/**\\/*.js'\n */\n input?: string | string[];\n\n /**\n * Output file path.\n * Use $1 as placeholder for input filename in multi-file scenarios.\n * Can be a single file, array of files, or pattern with $1.\n *\n * @example\n * - 'dist/bundle.min.js'\n * - ['file1.min.js', 'file2.min.js']\n * - '$1.min.js' (creates app.min.js from app.js)\n */\n output?: string | string[];\n\n /**\n * Compressor-specific options.\n * See individual compressor documentation for available options.\n */\n options?: TOptions;\n\n /**\n * CLI option string (used by CLI only).\n * @internal\n */\n option?: string;\n\n /**\n * Buffer size for file operations (in bytes).\n * @default 1024000 (1MB)\n */\n buffer?: number;\n\n /**\n * Timeout for the compressor process (in milliseconds).\n * If execution exceeds this limit, the process will be killed.\n */\n timeout?: number;\n\n /**\n * File type for compressors that support multiple types.\n * Required for YUI compressor.\n */\n type?: FileType;\n\n /**\n * Suppress console output.\n * @default false\n */\n silence?: boolean;\n\n /**\n * Public folder to prepend to input paths.\n *\n * @example\n * With publicFolder: 'public/js/' and input: 'app.js',\n * the actual path becomes 'public/js/app.js'\n */\n publicFolder?: string;\n\n /**\n * Replace files in place instead of creating new output files.\n * @default false\n */\n replaceInPlace?: boolean;\n\n /**\n * Allow empty output without throwing an error.\n * When true, if minification results in empty content, the output file will not be written.\n * Useful for CSS files containing only comments that get stripped.\n * @default false\n */\n allowEmptyOutput?: boolean;\n};\n\n/**\n * Options passed to compressor functions internally.\n * This is what compressors receive, not what users pass.\n */\nexport type MinifierOptions<\n TOptions extends CompressorOptions = CompressorOptions,\n> = {\n /**\n * The full settings object.\n */\n settings: Settings<TOptions>;\n\n /**\n * The content to minify.\n * For text-based formats (JS, CSS, HTML, SVG): string\n * For binary formats (images): Buffer\n * For multiple binary files: Buffer[]\n */\n content?: string | Buffer | Buffer[];\n\n /**\n * Index of current file when processing multiple files.\n */\n index?: number;\n};\n\n/**\n * Result returned after compression (used by CLI).\n */\nexport type Result = {\n /**\n * Label of the compressor used.\n */\n compressorLabel: string;\n\n /**\n * Size of minified content (formatted string, e.g., \"1.5 KB\").\n */\n size: string;\n\n /**\n * Gzipped size of minified content (formatted string).\n */\n sizeGzip: string;\n};\n\n/**\n * Type alias for user convenience.\n * @deprecated Use `Settings` instead. Will be removed in v11.\n */\nexport type MinifyOptions<\n TOptions extends CompressorOptions = CompressorOptions,\n> = Settings<TOptions>;\n"],"mappings":";;;;;AAmOsC,KAtM1BE,gBAAAA,GAsM0B;;;;;;;;;oBA7LhBC;;;;;KAMVC,gBAAAA;;;;;;;;;;;;;;;;WAgBCD;;;;;;;;YAQCD;;;;;;KAOFG,iBAAAA,GAAoBC;;;;;;KAOpBC,4BAA4BF,oBAAoBA,4BACjDI,gBAAgBD,cAAcE,QAAQN;;;;KAKrCO,QAAAA;;;;;;;;;;;;;;;;;;KAmBAC,0BAA0BP,oBAAoBA;;;;cAI1CE,WAAWC;;;;;;;;;;;;;qBAaJL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA6BTK;;;;;;;;;;;;;;;;;;;;;;;;SAwBHG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoCCF,iCACSJ,oBAAoBA;;;;YAK3BO,SAASJ;;;;;;;;qBAQAL,SAASA"}
|
package/dist/types.d.ts
CHANGED
package/dist/wildcards.d.ts
CHANGED
package/dist/wildcards.js
CHANGED
package/dist/wildcards.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wildcards.js","names":[],"sources":["../src/wildcards.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-
|
|
1
|
+
{"version":3,"file":"wildcards.js","names":[],"sources":["../src/wildcards.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport os from \"node:os\";\nimport fg from \"fast-glob\";\n\n/**\n * Check if the platform is Windows\n */\nfunction isWindows() {\n return os.platform() === \"win32\";\n}\n\n/**\n * Handle wildcards in a path, get the real path of each file.\n * @param input - Path with wildcards\n * @param publicFolder - Path to the public folder\n */\nexport function wildcards(input: string | string[], publicFolder?: string) {\n if (Array.isArray(input)) {\n return wildcardsArray(input, publicFolder);\n }\n\n return wildcardsString(input, publicFolder);\n}\n\n/**\n * Handle wildcards in a path (string only), get the real path of each file.\n * @param input - Path with wildcards\n * @param publicFolder - Path to the public folder\n */\nfunction wildcardsString(input: string, publicFolder?: string) {\n if (!input.includes(\"*\")) {\n return {};\n }\n\n const files = getFilesFromWildcards(input, publicFolder);\n const finalPaths = files.filter((path: string) => !path.includes(\"*\"));\n\n return {\n input: finalPaths,\n };\n}\n\n/**\n * Handle wildcards in a path (array only), get the real path of each file.\n * @param input - Array of paths with wildcards\n * @param publicFolder - Path to the public folder\n */\nfunction wildcardsArray(input: string[], publicFolder?: string) {\n // Convert input paths to patterns with public folder prefix\n const inputWithPublicFolder = input.map((item) => {\n const input2 = publicFolder ? publicFolder + item : item;\n return isWindows() ? fg.convertPathToPattern(input2) : input2;\n });\n\n // Check if any wildcards exist\n const hasWildcards = inputWithPublicFolder.some((item) =>\n item.includes(\"*\")\n );\n\n // Process paths based on whether wildcards exist\n const processedPaths = hasWildcards\n ? fg.globSync(inputWithPublicFolder)\n : input;\n\n // Filter out any remaining paths with wildcards\n const finalPaths = processedPaths.filter(\n (path: string) => !path.includes(\"*\")\n );\n\n return { input: finalPaths };\n}\n\n/**\n * Get the real path of each file.\n * @param input - Path with wildcards\n * @param publicFolder - Path to the public folder\n */\nfunction getFilesFromWildcards(input: string, publicFolder?: string) {\n const fullPath = publicFolder ? `${publicFolder}${input}` : input;\n return fg.globSync(\n isWindows() ? fg.convertPathToPattern(fullPath) : fullPath\n );\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAS,YAAY;AACjB,QAAO,GAAG,UAAU,KAAK;;;;;;;AAQ7B,SAAgB,UAAU,OAA0B,cAAuB;AACvE,KAAI,MAAM,QAAQ,MAAM,CACpB,QAAO,eAAe,OAAO,aAAa;AAG9C,QAAO,gBAAgB,OAAO,aAAa;;;;;;;AAQ/C,SAAS,gBAAgB,OAAe,cAAuB;AAC3D,KAAI,CAAC,MAAM,SAAS,IAAI,CACpB,QAAO,EAAE;AAMb,QAAO,EACH,OAJU,sBAAsB,OAAO,aAAa,CAC/B,QAAQ,SAAiB,CAAC,KAAK,SAAS,IAAI,CAAC,EAIrE;;;;;;;AAQL,SAAS,eAAe,OAAiB,cAAuB;CAE5D,MAAM,wBAAwB,MAAM,KAAK,SAAS;EAC9C,MAAM,SAAS,eAAe,eAAe,OAAO;AACpD,SAAO,WAAW,GAAG,GAAG,qBAAqB,OAAO,GAAG;GACzD;AAiBF,QAAO,EAAE,QAdY,sBAAsB,MAAM,SAC7C,KAAK,SAAS,IAAI,CACrB,GAIK,GAAG,SAAS,sBAAsB,GAClC,OAG4B,QAC7B,SAAiB,CAAC,KAAK,SAAS,IAAI,CACxC,EAE2B;;;;;;;AAQhC,SAAS,sBAAsB,OAAe,cAAuB;CACjE,MAAM,WAAW,eAAe,GAAG,eAAe,UAAU;AAC5D,QAAO,GAAG,SACN,WAAW,GAAG,GAAG,qBAAqB,SAAS,GAAG,SACrD"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { n as ValidationError, t as FileOperationError } from "./error-CUgKxOvI.js";
|
|
2
|
+
import { writeFileSync } from "node:fs";
|
|
3
|
+
import { writeFile } from "node:fs/promises";
|
|
4
|
+
|
|
5
|
+
//#region src/writeFile.ts
|
|
6
|
+
/*!
|
|
7
|
+
* node-minify
|
|
8
|
+
* Copyright (c) 2011-2026 Rodolphe Stoclin
|
|
9
|
+
* MIT Licensed
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Write provided content to a target file.
|
|
13
|
+
*
|
|
14
|
+
* When `file` is an array and `index` is provided, the file at that index is used; otherwise `file` is used directly.
|
|
15
|
+
*
|
|
16
|
+
* @param file - Target path or array of target paths
|
|
17
|
+
* @param content - Content to write; may be a `string` or `Buffer`
|
|
18
|
+
* @param index - Optional index to select a file when `file` is an array
|
|
19
|
+
* @returns The same `content` value that was written
|
|
20
|
+
* @throws ValidationError If no target file, no content, or the resolved target path is invalid
|
|
21
|
+
* @throws FileOperationError If the underlying filesystem write fails (wraps the original error)
|
|
22
|
+
*/
|
|
23
|
+
function writeFile$1({ file, content, index }) {
|
|
24
|
+
try {
|
|
25
|
+
const targetFile = resolveTargetFile(file, index);
|
|
26
|
+
validateContent(content);
|
|
27
|
+
writeFileSync(targetFile, content, Buffer.isBuffer(content) ? void 0 : "utf8");
|
|
28
|
+
return content;
|
|
29
|
+
} catch (error) {
|
|
30
|
+
handleWriteError(error, file);
|
|
31
|
+
return content;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Write content to a resolved target file path.
|
|
36
|
+
*
|
|
37
|
+
* Resolves the target from `file` (string or array) using `index` when provided, validates the content,
|
|
38
|
+
* ensures the target is not a directory, and writes the content to disk.
|
|
39
|
+
*
|
|
40
|
+
* @param file - Target path or array of target paths; when `file` is an array, `index` selects the entry
|
|
41
|
+
* @param content - Content to write; a `string` or `Buffer`
|
|
42
|
+
* @param index - Optional index used to select a file when `file` is an array
|
|
43
|
+
* @returns The same `content` value that was written
|
|
44
|
+
* @throws ValidationError If no target file, no content, or the resolved target path is invalid
|
|
45
|
+
* @throws FileOperationError If the underlying filesystem write fails (wraps the original error)
|
|
46
|
+
*/
|
|
47
|
+
async function writeFileAsync({ file, content, index }) {
|
|
48
|
+
try {
|
|
49
|
+
const targetFile = resolveTargetFile(file, index);
|
|
50
|
+
validateContent(content);
|
|
51
|
+
await writeFile(targetFile, content, Buffer.isBuffer(content) ? void 0 : "utf8");
|
|
52
|
+
return content;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
handleWriteError(error, file);
|
|
55
|
+
return content;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolve a target file path from a string or an array of paths, optionally selecting by index.
|
|
60
|
+
*
|
|
61
|
+
* @param file - A file path or an array of file paths to resolve from.
|
|
62
|
+
* @param index - Optional index to select an entry when `file` is an array; ignored if not provided.
|
|
63
|
+
* @returns The resolved file path.
|
|
64
|
+
* @throws ValidationError if no file is provided or the resolved target is not a string.
|
|
65
|
+
*/
|
|
66
|
+
function resolveTargetFile(file, index) {
|
|
67
|
+
if (!file) throw new ValidationError("No target file provided");
|
|
68
|
+
const targetFile = index !== void 0 ? Array.isArray(file) ? file[index] : file : file;
|
|
69
|
+
if (typeof targetFile !== "string") throw new ValidationError("Invalid target file path");
|
|
70
|
+
return targetFile;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Ensure content is present before writing.
|
|
74
|
+
*
|
|
75
|
+
* @param content - The data to write; a string or Buffer
|
|
76
|
+
* @throws ValidationError if `content` is empty or otherwise falsy
|
|
77
|
+
*/
|
|
78
|
+
function validateContent(content) {
|
|
79
|
+
if (!content) throw new ValidationError("No content provided");
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Normalize and rethrow errors that occur while attempting to write to one or more files.
|
|
83
|
+
*
|
|
84
|
+
* @param error - The original error thrown during the write attempt
|
|
85
|
+
* @param file - The target file path or an array of paths that were the intended write targets
|
|
86
|
+
* @throws ValidationError - rethrows the provided ValidationError without modification
|
|
87
|
+
* @throws FileOperationError - thrown for any other error, wrapping the original error with context about the write operation and the target file(s)
|
|
88
|
+
*/
|
|
89
|
+
function handleWriteError(error, file) {
|
|
90
|
+
if (error instanceof ValidationError) throw error;
|
|
91
|
+
throw new FileOperationError("write to", typeof file === "string" ? file : "multiple files", error);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
//#endregion
|
|
95
|
+
export { writeFileAsync as n, writeFile$1 as t };
|
|
96
|
+
//# sourceMappingURL=writeFile-mfUS3rMz.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"writeFile-mfUS3rMz.js","names":["writeFile","writeFileFs"],"sources":["../src/writeFile.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\nimport { writeFileSync } from \"node:fs\";\nimport { writeFile as writeFileFs } from \"node:fs/promises\";\nimport { FileOperationError, ValidationError } from \"./error.ts\";\n\ninterface WriteFileParams {\n file: string | string[];\n content: string | Buffer;\n index?: number;\n}\n\n/**\n * Write provided content to a target file.\n *\n * When `file` is an array and `index` is provided, the file at that index is used; otherwise `file` is used directly.\n *\n * @param file - Target path or array of target paths\n * @param content - Content to write; may be a `string` or `Buffer`\n * @param index - Optional index to select a file when `file` is an array\n * @returns The same `content` value that was written\n * @throws ValidationError If no target file, no content, or the resolved target path is invalid\n * @throws FileOperationError If the underlying filesystem write fails (wraps the original error)\n */\nexport function writeFile({\n file,\n content,\n index,\n}: WriteFileParams): string | Buffer {\n try {\n const targetFile = resolveTargetFile(file, index);\n validateContent(content);\n\n writeFileSync(\n targetFile,\n content,\n Buffer.isBuffer(content) ? undefined : \"utf8\"\n );\n return content;\n } catch (error) {\n handleWriteError(error, file);\n return content; // Should be unreachable due to handleWriteError throwing\n }\n}\n\n/**\n * Write content to a resolved target file path.\n *\n * Resolves the target from `file` (string or array) using `index` when provided, validates the content,\n * ensures the target is not a directory, and writes the content to disk.\n *\n * @param file - Target path or array of target paths; when `file` is an array, `index` selects the entry\n * @param content - Content to write; a `string` or `Buffer`\n * @param index - Optional index used to select a file when `file` is an array\n * @returns The same `content` value that was written\n * @throws ValidationError If no target file, no content, or the resolved target path is invalid\n * @throws FileOperationError If the underlying filesystem write fails (wraps the original error)\n */\nexport async function writeFileAsync({\n file,\n content,\n index,\n}: WriteFileParams): Promise<string | Buffer> {\n try {\n const targetFile = resolveTargetFile(file, index);\n validateContent(content);\n\n await writeFileFs(\n targetFile,\n content,\n Buffer.isBuffer(content) ? undefined : \"utf8\"\n );\n return content;\n } catch (error) {\n handleWriteError(error, file);\n return content; // Should be unreachable due to handleWriteError throwing\n }\n}\n\n/**\n * Resolve a target file path from a string or an array of paths, optionally selecting by index.\n *\n * @param file - A file path or an array of file paths to resolve from.\n * @param index - Optional index to select an entry when `file` is an array; ignored if not provided.\n * @returns The resolved file path.\n * @throws ValidationError if no file is provided or the resolved target is not a string.\n */\nfunction resolveTargetFile(file: string | string[], index?: number): string {\n if (!file) {\n throw new ValidationError(\"No target file provided\");\n }\n\n const targetFile =\n index !== undefined ? (Array.isArray(file) ? file[index] : file) : file;\n\n if (typeof targetFile !== \"string\") {\n throw new ValidationError(\"Invalid target file path\");\n }\n\n return targetFile;\n}\n\n/**\n * Ensure content is present before writing.\n *\n * @param content - The data to write; a string or Buffer\n * @throws ValidationError if `content` is empty or otherwise falsy\n */\nfunction validateContent(content: string | Buffer): void {\n if (!content) {\n throw new ValidationError(\"No content provided\");\n }\n}\n\n/**\n * Normalize and rethrow errors that occur while attempting to write to one or more files.\n *\n * @param error - The original error thrown during the write attempt\n * @param file - The target file path or an array of paths that were the intended write targets\n * @throws ValidationError - rethrows the provided ValidationError without modification\n * @throws FileOperationError - thrown for any other error, wrapping the original error with context about the write operation and the target file(s)\n */\nfunction handleWriteError(error: unknown, file: string | string[]): never {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new FileOperationError(\n \"write to\",\n typeof file === \"string\" ? file : \"multiple files\",\n error as Error\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgBA,YAAU,EACtB,MACA,SACA,SACiC;AACjC,KAAI;EACA,MAAM,aAAa,kBAAkB,MAAM,MAAM;AACjD,kBAAgB,QAAQ;AAExB,gBACI,YACA,SACA,OAAO,SAAS,QAAQ,GAAG,SAAY,OAC1C;AACD,SAAO;UACF,OAAO;AACZ,mBAAiB,OAAO,KAAK;AAC7B,SAAO;;;;;;;;;;;;;;;;AAiBf,eAAsB,eAAe,EACjC,MACA,SACA,SAC0C;AAC1C,KAAI;EACA,MAAM,aAAa,kBAAkB,MAAM,MAAM;AACjD,kBAAgB,QAAQ;AAExB,QAAMC,UACF,YACA,SACA,OAAO,SAAS,QAAQ,GAAG,SAAY,OAC1C;AACD,SAAO;UACF,OAAO;AACZ,mBAAiB,OAAO,KAAK;AAC7B,SAAO;;;;;;;;;;;AAYf,SAAS,kBAAkB,MAAyB,OAAwB;AACxE,KAAI,CAAC,KACD,OAAM,IAAI,gBAAgB,0BAA0B;CAGxD,MAAM,aACF,UAAU,SAAa,MAAM,QAAQ,KAAK,GAAG,KAAK,SAAS,OAAQ;AAEvE,KAAI,OAAO,eAAe,SACtB,OAAM,IAAI,gBAAgB,2BAA2B;AAGzD,QAAO;;;;;;;;AASX,SAAS,gBAAgB,SAAgC;AACrD,KAAI,CAAC,QACD,OAAM,IAAI,gBAAgB,sBAAsB;;;;;;;;;;AAYxD,SAAS,iBAAiB,OAAgB,MAAgC;AACtE,KAAI,iBAAiB,gBACjB,OAAM;AAEV,OAAM,IAAI,mBACN,YACA,OAAO,SAAS,WAAW,OAAO,kBAClC,MACH"}
|
package/dist/writeFile.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region src/writeFile.d.ts
|
|
2
2
|
/*!
|
|
3
3
|
* node-minify
|
|
4
|
-
* Copyright(c) 2011-
|
|
4
|
+
* Copyright (c) 2011-2026 Rodolphe Stoclin
|
|
5
5
|
* MIT Licensed
|
|
6
6
|
*/
|
|
7
7
|
interface WriteFileParams {
|
|
@@ -26,6 +26,24 @@ declare function writeFile({
|
|
|
26
26
|
content,
|
|
27
27
|
index
|
|
28
28
|
}: WriteFileParams): string | Buffer;
|
|
29
|
+
/**
|
|
30
|
+
* Write content to a resolved target file path.
|
|
31
|
+
*
|
|
32
|
+
* Resolves the target from `file` (string or array) using `index` when provided, validates the content,
|
|
33
|
+
* ensures the target is not a directory, and writes the content to disk.
|
|
34
|
+
*
|
|
35
|
+
* @param file - Target path or array of target paths; when `file` is an array, `index` selects the entry
|
|
36
|
+
* @param content - Content to write; a `string` or `Buffer`
|
|
37
|
+
* @param index - Optional index used to select a file when `file` is an array
|
|
38
|
+
* @returns The same `content` value that was written
|
|
39
|
+
* @throws ValidationError If no target file, no content, or the resolved target path is invalid
|
|
40
|
+
* @throws FileOperationError If the underlying filesystem write fails (wraps the original error)
|
|
41
|
+
*/
|
|
42
|
+
declare function writeFileAsync({
|
|
43
|
+
file,
|
|
44
|
+
content,
|
|
45
|
+
index
|
|
46
|
+
}: WriteFileParams): Promise<string | Buffer>;
|
|
29
47
|
//#endregion
|
|
30
|
-
export { writeFile };
|
|
48
|
+
export { writeFile, writeFileAsync };
|
|
31
49
|
//# sourceMappingURL=writeFile.d.ts.map
|
package/dist/writeFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeFile.d.ts","names":[],"sources":["../src/writeFile.ts"],"sourcesContent":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"writeFile.d.ts","names":[],"sources":["../src/writeFile.ts"],"sourcesContent":[],"mappings":";;;AA4BA;;;UAlBU,eAAA,CAqBN;EACD,IAAA,EAAA,MAAA,GAAA,MAAA,EAAA;EAA2B,OAAA,EAAA,MAAA,GApBR,MAoBQ;EAAM,KAAA,CAAA,EAAA,MAAA;AA8BpC;;;;;;;;;;;;;iBAlCgB,SAAA;;;;GAIb,2BAA2B;;;;;;;;;;;;;;iBA8BR,cAAA;;;;GAInB,kBAAkB,iBAAiB"}
|
package/dist/writeFile.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as writeFile } from "./writeFile-
|
|
1
|
+
import { n as writeFileAsync, t as writeFile } from "./writeFile-mfUS3rMz.js";
|
|
2
2
|
|
|
3
|
-
export { writeFile };
|
|
3
|
+
export { writeFile, writeFileAsync };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@node-minify/utils",
|
|
3
|
-
"version": "10.
|
|
3
|
+
"version": "10.4.0",
|
|
4
4
|
"description": "utils for @node-minify",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"compressor",
|
|
@@ -56,6 +56,6 @@
|
|
|
56
56
|
"gzip-size": "7.0.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@node-minify/types": "10.
|
|
59
|
+
"@node-minify/types": "10.4.0"
|
|
60
60
|
}
|
|
61
61
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-Ck87RwDD.js","names":[],"sources":["../src/error.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Error class for file operation failures.\n * @extends Error\n */\nexport class FileOperationError extends Error {\n constructor(operation: string, path: string, originalError?: Error) {\n super(\n `Failed to ${operation} file ${path}: ${originalError?.message || \"\"}`\n );\n this.name = \"FileOperationError\";\n }\n}\n\n/**\n * Error class for validation failures.\n * @extends Error\n */\nexport class ValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ValidationError\";\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAa,qBAAb,cAAwC,MAAM;CAC1C,YAAY,WAAmB,MAAc,eAAuB;AAChE,QACI,aAAa,UAAU,QAAQ,KAAK,IAAI,eAAe,WAAW,KACrE;AACD,OAAK,OAAO;;;;;;;AAQpB,IAAa,kBAAb,cAAqC,MAAM;CACvC,YAAY,SAAiB;AACzB,QAAM,QAAQ;AACd,OAAK,OAAO"}
|