@node-minify/core 10.2.0 → 10.3.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/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -21
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/LICENSE
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -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.
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["CompressorReturnType","ImageFormat","CompressorOutput","Buffer","CompressorResult","CompressorOptions","Record","Compressor","TOptions","MinifierOptions","Promise","FileType","Settings","Result","MinifyOptions"],"sources":["../../types/src/types.d.ts","../src/index.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["CompressorReturnType","ImageFormat","CompressorOutput","Buffer","CompressorResult","CompressorOptions","Record","Compressor","TOptions","MinifierOptions","Promise","FileType","Settings","Result","MinifyOptions"],"sources":["../../types/src/types.d.ts","../src/index.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/**\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":";;;;;AA2NsC,KA9L1BE,gBAAAA,GA8L0B;;;;ECvMhB,MAAA,CAAA,EAAM,MAAA;;EAA+B;;;EAExD,OAAA,EAAA,MAAA,GDgBmBC,MChBnB;CAAO;;;;KDsBEC,gBAAAA;;;;;;;;;;;;;;;;WAgBCD;;;;;;;;YAQCD;;;;;;KAOFG,iBAAAA,GAAoBC;;;;;;KAOpBC,4BAA4BF,oBAAoBA,4BACjDI,gBAAgBD,cAAcE,QAAQN;;;;KAKrCO,QAAAA;;;;;;;;;;;;;;;;;;KAmBAC,0BAA0BP,oBAAoBA;;;;cAI1CE,WAAWC;;;;;;;;;;;;;qBAaJL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YA6BTK;;;;;;;;;;;;;;;;;;;;;;;;SAwBHG;;;;;;;;;;;;;;;;;;;;;;;;;;;KA4BCF,iCACSJ,oBAAoBA;;;;YAK3BO,SAASJ;;;;;;;;qBAQAL,SAASA;;;;;;;;;;;;AAnIhC;AAmBA;;AAA0DE,iBCvFpC,MDuFoCA,CAAAA,UCvFnB,iBDuFmBA,GCvFC,iBDuFDA,CAAAA,CAAAA,QAAAA,ECtF5C,QDsF4CA,CCtFnC,CDsFmCA,CAAAA,CAAAA,ECrFvD,ODqFuDA,CAAAA,MAAAA,CAAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,7 @@
|
|
|
1
|
-
import { compressSingleFile, getContentFromFilesAsync, run, setFileNameMin, setPublicFolder, wildcards } from "@node-minify/utils";
|
|
2
|
-
import fs from "node:fs";
|
|
1
|
+
import { compressSingleFile, getContentFromFilesAsync, isImageFile, readFileAsync, run, setFileNameMin, setPublicFolder, wildcards } from "@node-minify/utils";
|
|
3
2
|
import { mkdirp } from "mkdirp";
|
|
4
3
|
|
|
5
4
|
//#region src/compress.ts
|
|
6
|
-
/*!
|
|
7
|
-
* node-minify
|
|
8
|
-
* Copyright(c) 2011-2025 Rodolphe Stoclin
|
|
9
|
-
* MIT Licensed
|
|
10
|
-
*/
|
|
11
|
-
/**
|
|
12
|
-
* Module dependencies.
|
|
13
|
-
*/
|
|
14
5
|
/**
|
|
15
6
|
* Run the compressor using the provided settings.
|
|
16
7
|
*
|
|
@@ -25,7 +16,7 @@ async function compress(settings) {
|
|
|
25
16
|
if (!Array.isArray(settings.input)) throw new Error("When output is an array, input must also be an array");
|
|
26
17
|
if (settings.input.length !== settings.output.length) throw new Error(`Input and output arrays must have the same length (input: ${settings.input.length}, output: ${settings.output.length})`);
|
|
27
18
|
}
|
|
28
|
-
if (settings.output) createDirectory(settings.output);
|
|
19
|
+
if (settings.output) await createDirectory(settings.output);
|
|
29
20
|
if (Array.isArray(settings.output)) return compressArrayOfFiles(settings);
|
|
30
21
|
return compressSingleFile(settings);
|
|
31
22
|
}
|
|
@@ -44,7 +35,7 @@ async function compressArrayOfFiles(settings) {
|
|
|
44
35
|
const compressionTasks = inputs.map(async (input, index) => {
|
|
45
36
|
return run({
|
|
46
37
|
settings,
|
|
47
|
-
content: await getContentFromFilesAsync(input),
|
|
38
|
+
content: isImageFile(input) ? await readFileAsync(input, true) : await getContentFromFilesAsync(input),
|
|
48
39
|
index
|
|
49
40
|
});
|
|
50
41
|
});
|
|
@@ -55,22 +46,17 @@ async function compressArrayOfFiles(settings) {
|
|
|
55
46
|
* Create folder of the target file.
|
|
56
47
|
* @param filePath Full path of the file (can be string or array when $1 pattern is used)
|
|
57
48
|
*/
|
|
58
|
-
function createDirectory(filePath) {
|
|
49
|
+
async function createDirectory(filePath) {
|
|
59
50
|
if (!filePath) return;
|
|
60
51
|
const paths = Array.isArray(filePath) ? filePath : [filePath];
|
|
52
|
+
const uniqueDirs = /* @__PURE__ */ new Set();
|
|
61
53
|
for (const path of paths) {
|
|
62
54
|
if (typeof path !== "string") continue;
|
|
63
55
|
const dirPath = path.substring(0, path.lastIndexOf("/"));
|
|
64
56
|
if (!dirPath) continue;
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
function directoryExists(path) {
|
|
69
|
-
try {
|
|
70
|
-
return fs.statSync(path).isDirectory();
|
|
71
|
-
} catch {
|
|
72
|
-
return false;
|
|
57
|
+
uniqueDirs.add(dirPath);
|
|
73
58
|
}
|
|
59
|
+
await Promise.all(Array.from(uniqueDirs).map((dir) => mkdirp(dir)));
|
|
74
60
|
}
|
|
75
61
|
|
|
76
62
|
//#endregion
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["defaultSettings: Partial<Settings>","settings: Settings<T>"],"sources":["../src/compress.ts","../src/setup.ts","../src/index.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport fs from \"node:fs\";\nimport type {\n CompressorOptions,\n MinifierOptions,\n Settings,\n} from \"@node-minify/types\";\nimport {\n compressSingleFile,\n getContentFromFilesAsync,\n run,\n} from \"@node-minify/utils\";\nimport { mkdirp } from \"mkdirp\";\n\n/**\n * Run the compressor using the provided settings.\n *\n * Validates settings when `output` is an array (requires `input` to be an array with the same length) and ensures target output directories exist before processing. Dispatches either multi-file or single-file compression based on `settings.output`.\n *\n * @param settings - Compression settings including `input`, `output`, and compressor-specific options\n * @returns The resulting compressed output string for a single output, or the last result produced when processing multiple outputs (or an empty string if no results were produced)\n * @throws Error - If `output` is an array but `input` is not, or if `input` and `output` arrays have differing lengths\n */\nexport async function compress<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): Promise<string> {\n if (Array.isArray(settings.output)) {\n if (!Array.isArray(settings.input)) {\n throw new Error(\n \"When output is an array, input must also be an array\"\n );\n }\n if (settings.input.length !== settings.output.length) {\n throw new Error(\n `Input and output arrays must have the same length (input: ${settings.input.length}, output: ${settings.output.length})`\n );\n }\n }\n\n if (settings.output) {\n createDirectory(settings.output);\n }\n\n // Handle array outputs (from user input or created internally by checkOutput when processing $1 pattern)\n if (Array.isArray(settings.output)) {\n return compressArrayOfFiles(settings);\n }\n\n return compressSingleFile(settings as Settings);\n}\n\n/**\n * Compress multiple input files specified in the settings.\n *\n * @param settings - Configuration object where `settings.input` and `settings.output` are arrays of equal length; each `settings.input[i]` is a file path to compress and corresponds to `settings.output[i]`.\n * @returns The result of the last compression task, or an empty string if no tasks ran.\n * @throws Error if any entry in `settings.input` is not a non-empty string.\n */\nasync function compressArrayOfFiles<\n T extends CompressorOptions = CompressorOptions,\n>(settings: Settings<T>): Promise<string> {\n const inputs = settings.input as string[];\n\n inputs.forEach((input, index) => {\n if (!input || typeof input !== \"string\") {\n throw new Error(\n `Invalid input at index ${index}: expected non-empty string, got ${\n typeof input === \"string\" ? \"empty string\" : typeof input\n }`\n );\n }\n });\n\n const compressionTasks = inputs.map(async (input, index) => {\n const content = await getContentFromFilesAsync(input);\n return run({ settings, content, index } as MinifierOptions<T>);\n });\n\n const results = await Promise.all(compressionTasks);\n return results[results.length - 1] ?? \"\";\n}\n\n/**\n * Create folder of the target file.\n * @param filePath Full path of the file (can be string or array when $1 pattern is used)\n */\nfunction createDirectory(filePath: string | string[]) {\n // Early return if no file path provided\n if (!filePath) {\n return;\n }\n\n // Handle array (created internally by checkOutput when processing $1 pattern)\n const paths = Array.isArray(filePath) ? filePath : [filePath];\n\n for (const path of paths) {\n if (typeof path !== \"string\") {\n continue;\n }\n\n // Extract directory path\n const dirPath = path.substring(0, path.lastIndexOf(\"/\"));\n\n // Early return if no directory path\n if (!dirPath) {\n continue;\n }\n\n // Create directory if it doesn't exist\n if (!directoryExists(dirPath)) {\n mkdirp.sync(dirPath);\n }\n }\n}\n\n// Helper function to check if directory exists\nfunction directoryExists(path: string): boolean {\n try {\n return fs.statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n","/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport type { CompressorOptions, Settings } from \"@node-minify/types\";\nimport { setFileNameMin, setPublicFolder, wildcards } from \"@node-minify/utils\";\n\n/**\n * Default settings.\n */\nconst defaultSettings: Partial<Settings> = {\n options: {},\n buffer: 1000 * 1024,\n};\n\n/**\n * Builds and validates the final Settings object by merging defaults with user input.\n *\n * @param inputSettings - User-provided settings that override defaults\n * @returns The validated and enhanced Settings object ready for use\n */\nfunction setup<T extends CompressorOptions = CompressorOptions>(\n inputSettings: Settings<T>\n): Settings<T> {\n const settings: Settings<T> = {\n ...structuredClone(defaultSettings),\n ...inputSettings,\n } as Settings<T>;\n\n // In memory\n if (settings.content) {\n validateMandatoryFields(inputSettings, [\"compressor\", \"content\"]);\n return settings;\n }\n\n validateMandatoryFields(inputSettings, [\"compressor\", \"input\", \"output\"]);\n\n if (Array.isArray(settings.input)) {\n settings.input.forEach((input, index) => {\n if (!input || typeof input !== \"string\") {\n throw new Error(\n `Invalid input at index ${index}: expected non-empty string, got ${\n typeof input === \"string\"\n ? \"empty string\"\n : typeof input\n }`\n );\n }\n });\n }\n\n return enhanceSettings(settings);\n}\n\n/**\n * Augments a Settings object with derived values and normalized path outputs.\n *\n * Enhancements performed when applicable:\n * - Expands input patterns into concrete input entries.\n * - Computes output paths when a single output string contains the `$1` placeholder, producing per-input outputs.\n * - Resolves and attaches public-folder-related values derived from input and publicFolder.\n *\n * @param settings - The initial settings to enhance\n * @returns The enhanced Settings object with derived inputs, outputs, and public-folder values applied\n */\nfunction enhanceSettings<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): Settings<T> {\n let enhancedSettings = settings;\n\n if (enhancedSettings.input) {\n enhancedSettings = {\n ...enhancedSettings,\n ...wildcards(enhancedSettings.input, enhancedSettings.publicFolder),\n };\n }\n if (\n enhancedSettings.input &&\n enhancedSettings.output &&\n !Array.isArray(enhancedSettings.output)\n ) {\n enhancedSettings = {\n ...enhancedSettings,\n ...checkOutput(\n enhancedSettings.input,\n enhancedSettings.output,\n enhancedSettings.publicFolder,\n enhancedSettings.replaceInPlace\n ),\n };\n }\n if (enhancedSettings.input && enhancedSettings.publicFolder) {\n enhancedSettings = {\n ...enhancedSettings,\n ...setPublicFolder(\n enhancedSettings.input,\n enhancedSettings.publicFolder\n ),\n };\n }\n\n return enhancedSettings;\n}\n\n/**\n * Check the output path, searching for $1\n * if exist, returns the path replacing $1 by file name\n * @param input Path file\n * @param output Path to the output file\n * @param publicFolder Path to the public folder\n * @param replaceInPlace True to replace file in same folder\n * @returns Enhanced settings with processed output, or undefined if no processing needed\n */\nfunction checkOutput(\n input: string | string[],\n output: string | string[],\n publicFolder?: string,\n replaceInPlace?: boolean\n): { output: string | string[] } | undefined {\n // Arrays don't use the $1 placeholder pattern - they're handled directly in compress()\n if (Array.isArray(output)) {\n return undefined;\n }\n\n const PLACEHOLDER_PATTERN = /\\$1/;\n\n if (!PLACEHOLDER_PATTERN.test(output)) {\n return undefined;\n }\n\n const effectivePublicFolder = replaceInPlace ? undefined : publicFolder;\n\n // If array of files\n if (Array.isArray(input)) {\n const outputMin = input.map((file) =>\n setFileNameMin(file, output, effectivePublicFolder, replaceInPlace)\n );\n return { output: outputMin };\n }\n\n // Single file\n return {\n output: setFileNameMin(\n input,\n output,\n effectivePublicFolder,\n replaceInPlace\n ),\n };\n}\n\n/**\n * Ensure required settings are present and that `compressor` is a valid function.\n *\n * @param settings - Settings object to validate\n * @param fields - Names of required fields to check on `settings`\n * @throws Error if a required field is missing\n * @throws Error if `settings.compressor` is not a function\n */\nfunction validateMandatoryFields<\n T extends CompressorOptions = CompressorOptions,\n>(settings: Settings<T>, fields: string[]) {\n for (const field of fields) {\n mandatory(field, settings);\n }\n\n if (typeof settings.compressor !== \"function\") {\n throw new Error(\n \"compressor should be a function, maybe you forgot to install the compressor\"\n );\n }\n}\n\n/**\n * Check if the setting exists.\n * @param setting - Setting key to check\n * @param settings - Settings object\n */\nfunction mandatory(setting: string, settings: Record<string, unknown>) {\n if (!settings[setting]) {\n throw new Error(`${setting} is mandatory.`);\n }\n}\n\nexport { setup };\n","/*!\n * node-minify\n * Copyright(c) 2011-2025 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport type { CompressorOptions, Settings } from \"@node-minify/types\";\nimport { compressSingleFile } from \"@node-minify/utils\";\nimport { compress } from \"./compress.ts\";\nimport { setup } from \"./setup.ts\";\n\n/**\n * Minifies input according to the provided settings.\n *\n * @param settings - User-provided settings that specify the compressor, input/content, output and related options\n * @returns The minified content as a string\n */\nexport async function minify<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): Promise<string> {\n const compressorSettings = setup(settings);\n const method = settings.content ? compressSingleFile : compress;\n return await method(compressorSettings);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+BA,eAAsB,SAClB,UACe;AACf,KAAI,MAAM,QAAQ,SAAS,OAAO,EAAE;AAChC,MAAI,CAAC,MAAM,QAAQ,SAAS,MAAM,CAC9B,OAAM,IAAI,MACN,uDACH;AAEL,MAAI,SAAS,MAAM,WAAW,SAAS,OAAO,OAC1C,OAAM,IAAI,MACN,6DAA6D,SAAS,MAAM,OAAO,YAAY,SAAS,OAAO,OAAO,GACzH;;AAIT,KAAI,SAAS,OACT,iBAAgB,SAAS,OAAO;AAIpC,KAAI,MAAM,QAAQ,SAAS,OAAO,CAC9B,QAAO,qBAAqB,SAAS;AAGzC,QAAO,mBAAmB,SAAqB;;;;;;;;;AAUnD,eAAe,qBAEb,UAAwC;CACtC,MAAM,SAAS,SAAS;AAExB,QAAO,SAAS,OAAO,UAAU;AAC7B,MAAI,CAAC,SAAS,OAAO,UAAU,SAC3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|
|
1
|
+
{"version":3,"file":"index.js","names":["defaultSettings: Partial<Settings>","settings: Settings<T>"],"sources":["../src/compress.ts","../src/setup.ts","../src/index.ts"],"sourcesContent":["/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport type {\n CompressorOptions,\n MinifierOptions,\n Settings,\n} from \"@node-minify/types\";\nimport {\n compressSingleFile,\n getContentFromFilesAsync,\n isImageFile,\n readFileAsync,\n run,\n} from \"@node-minify/utils\";\nimport { mkdirp } from \"mkdirp\";\n\n/**\n * Run the compressor using the provided settings.\n *\n * Validates settings when `output` is an array (requires `input` to be an array with the same length) and ensures target output directories exist before processing. Dispatches either multi-file or single-file compression based on `settings.output`.\n *\n * @param settings - Compression settings including `input`, `output`, and compressor-specific options\n * @returns The resulting compressed output string for a single output, or the last result produced when processing multiple outputs (or an empty string if no results were produced)\n * @throws Error - If `output` is an array but `input` is not, or if `input` and `output` arrays have differing lengths\n */\nexport async function compress<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): Promise<string> {\n if (Array.isArray(settings.output)) {\n if (!Array.isArray(settings.input)) {\n throw new Error(\n \"When output is an array, input must also be an array\"\n );\n }\n if (settings.input.length !== settings.output.length) {\n throw new Error(\n `Input and output arrays must have the same length (input: ${settings.input.length}, output: ${settings.output.length})`\n );\n }\n }\n\n if (settings.output) {\n await createDirectory(settings.output);\n }\n\n // Handle array outputs (from user input or created internally by checkOutput when processing $1 pattern)\n if (Array.isArray(settings.output)) {\n return compressArrayOfFiles(settings);\n }\n\n return compressSingleFile(settings as Settings);\n}\n\n/**\n * Compress multiple input files specified in the settings.\n *\n * @param settings - Configuration object where `settings.input` and `settings.output` are arrays of equal length; each `settings.input[i]` is a file path to compress and corresponds to `settings.output[i]`.\n * @returns The result of the last compression task, or an empty string if no tasks ran.\n * @throws Error if any entry in `settings.input` is not a non-empty string.\n */\nasync function compressArrayOfFiles<\n T extends CompressorOptions = CompressorOptions,\n>(settings: Settings<T>): Promise<string> {\n const inputs = settings.input as string[];\n\n inputs.forEach((input, index) => {\n if (!input || typeof input !== \"string\") {\n throw new Error(\n `Invalid input at index ${index}: expected non-empty string, got ${\n typeof input === \"string\" ? \"empty string\" : typeof input\n }`\n );\n }\n });\n\n const compressionTasks = inputs.map(async (input, index) => {\n const content = isImageFile(input)\n ? await readFileAsync(input, true)\n : await getContentFromFilesAsync(input);\n return run({ settings, content, index } as MinifierOptions<T>);\n });\n\n const results = await Promise.all(compressionTasks);\n return results[results.length - 1] ?? \"\";\n}\n\n/**\n * Create folder of the target file.\n * @param filePath Full path of the file (can be string or array when $1 pattern is used)\n */\nasync function createDirectory(filePath: string | string[]) {\n // Early return if no file path provided\n if (!filePath) {\n return;\n }\n\n // Handle array (created internally by checkOutput when processing $1 pattern)\n const paths = Array.isArray(filePath) ? filePath : [filePath];\n const uniqueDirs = new Set<string>();\n\n for (const path of paths) {\n if (typeof path !== \"string\") {\n continue;\n }\n\n // Extract directory path\n const dirPath = path.substring(0, path.lastIndexOf(\"/\"));\n\n // Early return if no directory path\n if (!dirPath) {\n continue;\n }\n\n uniqueDirs.add(dirPath);\n }\n\n // Create directories in parallel\n await Promise.all(Array.from(uniqueDirs).map((dir) => mkdirp(dir)));\n}\n","/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport type { CompressorOptions, Settings } from \"@node-minify/types\";\nimport { setFileNameMin, setPublicFolder, wildcards } from \"@node-minify/utils\";\n\n/**\n * Default settings.\n */\nconst defaultSettings: Partial<Settings> = {\n options: {},\n buffer: 1000 * 1024,\n};\n\n/**\n * Builds and validates the final Settings object by merging defaults with user input.\n *\n * @param inputSettings - User-provided settings that override defaults\n * @returns The validated and enhanced Settings object ready for use\n */\nfunction setup<T extends CompressorOptions = CompressorOptions>(\n inputSettings: Settings<T>\n): Settings<T> {\n const settings: Settings<T> = {\n ...structuredClone(defaultSettings),\n ...inputSettings,\n } as Settings<T>;\n\n // In memory\n if (settings.content) {\n validateMandatoryFields(inputSettings, [\"compressor\", \"content\"]);\n return settings;\n }\n\n validateMandatoryFields(inputSettings, [\"compressor\", \"input\", \"output\"]);\n\n if (Array.isArray(settings.input)) {\n settings.input.forEach((input, index) => {\n if (!input || typeof input !== \"string\") {\n throw new Error(\n `Invalid input at index ${index}: expected non-empty string, got ${\n typeof input === \"string\"\n ? \"empty string\"\n : typeof input\n }`\n );\n }\n });\n }\n\n return enhanceSettings(settings);\n}\n\n/**\n * Augments a Settings object with derived values and normalized path outputs.\n *\n * Enhancements performed when applicable:\n * - Expands input patterns into concrete input entries.\n * - Computes output paths when a single output string contains the `$1` placeholder, producing per-input outputs.\n * - Resolves and attaches public-folder-related values derived from input and publicFolder.\n *\n * @param settings - The initial settings to enhance\n * @returns The enhanced Settings object with derived inputs, outputs, and public-folder values applied\n */\nfunction enhanceSettings<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): Settings<T> {\n let enhancedSettings = settings;\n\n if (enhancedSettings.input) {\n enhancedSettings = {\n ...enhancedSettings,\n ...wildcards(enhancedSettings.input, enhancedSettings.publicFolder),\n };\n }\n if (\n enhancedSettings.input &&\n enhancedSettings.output &&\n !Array.isArray(enhancedSettings.output)\n ) {\n enhancedSettings = {\n ...enhancedSettings,\n ...checkOutput(\n enhancedSettings.input,\n enhancedSettings.output,\n enhancedSettings.publicFolder,\n enhancedSettings.replaceInPlace\n ),\n };\n }\n if (enhancedSettings.input && enhancedSettings.publicFolder) {\n enhancedSettings = {\n ...enhancedSettings,\n ...setPublicFolder(\n enhancedSettings.input,\n enhancedSettings.publicFolder\n ),\n };\n }\n\n return enhancedSettings;\n}\n\n/**\n * Check the output path, searching for $1\n * if exist, returns the path replacing $1 by file name\n * @param input Path file\n * @param output Path to the output file\n * @param publicFolder Path to the public folder\n * @param replaceInPlace True to replace file in same folder\n * @returns Enhanced settings with processed output, or undefined if no processing needed\n */\nfunction checkOutput(\n input: string | string[],\n output: string | string[],\n publicFolder?: string,\n replaceInPlace?: boolean\n): { output: string | string[] } | undefined {\n // Arrays don't use the $1 placeholder pattern - they're handled directly in compress()\n if (Array.isArray(output)) {\n return undefined;\n }\n\n const PLACEHOLDER_PATTERN = /\\$1/;\n\n if (!PLACEHOLDER_PATTERN.test(output)) {\n return undefined;\n }\n\n const effectivePublicFolder = replaceInPlace ? undefined : publicFolder;\n\n // If array of files\n if (Array.isArray(input)) {\n const outputMin = input.map((file) =>\n setFileNameMin(file, output, effectivePublicFolder, replaceInPlace)\n );\n return { output: outputMin };\n }\n\n // Single file\n return {\n output: setFileNameMin(\n input,\n output,\n effectivePublicFolder,\n replaceInPlace\n ),\n };\n}\n\n/**\n * Ensure required settings are present and that `compressor` is a valid function.\n *\n * @param settings - Settings object to validate\n * @param fields - Names of required fields to check on `settings`\n * @throws Error if a required field is missing\n * @throws Error if `settings.compressor` is not a function\n */\nfunction validateMandatoryFields<\n T extends CompressorOptions = CompressorOptions,\n>(settings: Settings<T>, fields: string[]) {\n for (const field of fields) {\n mandatory(field, settings);\n }\n\n if (typeof settings.compressor !== \"function\") {\n throw new Error(\n \"compressor should be a function, maybe you forgot to install the compressor\"\n );\n }\n}\n\n/**\n * Check if the setting exists.\n * @param setting - Setting key to check\n * @param settings - Settings object\n */\nfunction mandatory(setting: string, settings: Record<string, unknown>) {\n if (!settings[setting]) {\n throw new Error(`${setting} is mandatory.`);\n }\n}\n\nexport { setup };\n","/*!\n * node-minify\n * Copyright (c) 2011-2026 Rodolphe Stoclin\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\nimport type { CompressorOptions, Settings } from \"@node-minify/types\";\nimport { compressSingleFile } from \"@node-minify/utils\";\nimport { compress } from \"./compress.ts\";\nimport { setup } from \"./setup.ts\";\n\n/**\n * Minifies input according to the provided settings.\n *\n * @param settings - User-provided settings that specify the compressor, input/content, output and related options\n * @returns The minified content as a string\n */\nexport async function minify<T extends CompressorOptions = CompressorOptions>(\n settings: Settings<T>\n): Promise<string> {\n const compressorSettings = setup(settings);\n const method = settings.content ? compressSingleFile : compress;\n return await method(compressorSettings);\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,eAAsB,SAClB,UACe;AACf,KAAI,MAAM,QAAQ,SAAS,OAAO,EAAE;AAChC,MAAI,CAAC,MAAM,QAAQ,SAAS,MAAM,CAC9B,OAAM,IAAI,MACN,uDACH;AAEL,MAAI,SAAS,MAAM,WAAW,SAAS,OAAO,OAC1C,OAAM,IAAI,MACN,6DAA6D,SAAS,MAAM,OAAO,YAAY,SAAS,OAAO,OAAO,GACzH;;AAIT,KAAI,SAAS,OACT,OAAM,gBAAgB,SAAS,OAAO;AAI1C,KAAI,MAAM,QAAQ,SAAS,OAAO,CAC9B,QAAO,qBAAqB,SAAS;AAGzC,QAAO,mBAAmB,SAAqB;;;;;;;;;AAUnD,eAAe,qBAEb,UAAwC;CACtC,MAAM,SAAS,SAAS;AAExB,QAAO,SAAS,OAAO,UAAU;AAC7B,MAAI,CAAC,SAAS,OAAO,UAAU,SAC3B,OAAM,IAAI,MACN,0BAA0B,MAAM,mCAC5B,OAAO,UAAU,WAAW,iBAAiB,OAAO,QAE3D;GAEP;CAEF,MAAM,mBAAmB,OAAO,IAAI,OAAO,OAAO,UAAU;AAIxD,SAAO,IAAI;GAAE;GAAU,SAHP,YAAY,MAAM,GAC5B,MAAM,cAAc,OAAO,KAAK,GAChC,MAAM,yBAAyB,MAAM;GACX;GAAO,CAAuB;GAChE;CAEF,MAAM,UAAU,MAAM,QAAQ,IAAI,iBAAiB;AACnD,QAAO,QAAQ,QAAQ,SAAS,MAAM;;;;;;AAO1C,eAAe,gBAAgB,UAA6B;AAExD,KAAI,CAAC,SACD;CAIJ,MAAM,QAAQ,MAAM,QAAQ,SAAS,GAAG,WAAW,CAAC,SAAS;CAC7D,MAAM,6BAAa,IAAI,KAAa;AAEpC,MAAK,MAAM,QAAQ,OAAO;AACtB,MAAI,OAAO,SAAS,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ACA,cACA,gBACyC;AAEzC,KAAI,MAAM,QAAQ,OAAO,CACrB;AAKJ,KAAI,CAFwB,MAEH,KAAK,OAAO,CACjC;CAGJ,MAAM,wBAAwB,iBAAiB,SAAY;AAG3D,KAAI,MAAM,QAAQ,MAAM,CAIpB,QAAO,EAAE,QAHS,MAAM,KAAK,SACzB,eAAe,MAAM,QAAQ,uBAAuB,eAAe,CACtE,EAC2B;AAIhC,QAAO,EACH,QAAQ,eACJ,OACA,QACA,uBACA,eACH,EACJ;;;;;;;;;;AAWL,SAAS,wBAEP,UAAuB,QAAkB;AACvC,MAAK,MAAM,SAAS,OAChB,WAAU,OAAO,SAAS;AAG9B,KAAI,OAAO,SAAS,eAAe,WAC/B,OAAM,IAAI,MACN,8EACH;;;;;;;AAST,SAAS,UAAU,SAAiB,UAAmC;AACnE,KAAI,CAAC,SAAS,SACV,OAAM,IAAI,MAAM,GAAG,QAAQ,gBAAgB;;;;;;;;;;;ACrKnD,eAAsB,OAClB,UACe;CACf,MAAM,qBAAqB,MAAM,SAAS;AAE1C,QAAO,OADQ,SAAS,UAAU,qBAAqB,UACnC,mBAAmB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@node-minify/core",
|
|
3
|
-
"version": "10.
|
|
3
|
+
"version": "10.3.0",
|
|
4
4
|
"description": "core of @node-minify",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"compressor",
|
|
@@ -51,10 +51,10 @@
|
|
|
51
51
|
"dev": "tsdown src/index.ts --watch"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@node-minify/utils": "10.
|
|
54
|
+
"@node-minify/utils": "10.3.0",
|
|
55
55
|
"mkdirp": "3.0.1"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
-
"@node-minify/types": "10.
|
|
58
|
+
"@node-minify/types": "10.3.0"
|
|
59
59
|
}
|
|
60
60
|
}
|