@medicomind/rolldown-compression 1.0.1 → 1.1.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/CHANGELOG.md +6 -0
- package/README.md +21 -3
- package/dist/index.cjs +173 -72
- package/dist/index.d.cts +10 -0
- package/dist/index.d.mts +10 -0
- package/dist/index.mjs +173 -72
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @medicomind/rolldown-compression
|
|
2
2
|
|
|
3
|
+
## 1.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [`1d98d99`](https://github.com/Medico-Mind/rolldown-compression/commit/1d98d995567280c60194451818c7caffb7808bc6) Thanks [@Mnwa](https://github.com/Mnwa)! - Add `stream` option: compress from disk in `writeBundle` (order `post`) instead of in memory in `generateBundle`. Files are read on demand in bounded batches (`chunkSize` source bytes per batch, or 4 MB when `chunkSize` is 0), so the whole build is never buffered by the plugin and assets written to disk by other plugins' `writeBundle` hooks are compressed as well — removing the previous `generateBundle`-only limitation.
|
|
8
|
+
|
|
3
9
|
## 1.0.1
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -57,6 +57,7 @@ compression({
|
|
|
57
57
|
skipIfLargerOrEqual: true,
|
|
58
58
|
concurrency: 0, // 0 = number of logical CPUs
|
|
59
59
|
chunkSize: 0, // 0 = compress everything in one batch
|
|
60
|
+
stream: false, // true = on-demand disk-based compression in writeBundle
|
|
60
61
|
logLevel: 'info',
|
|
61
62
|
})
|
|
62
63
|
```
|
|
@@ -91,7 +92,8 @@ export default defineConfig({
|
|
|
91
92
|
| `deleteOriginalAssets` | `boolean` | `false` | Remove the original from the bundle after all algorithms processed it. Errors if `filename` resolves to the source name. |
|
|
92
93
|
| `skipIfLargerOrEqual` | `boolean` | `true` | Don't emit artifacts whose compressed size is `>=` the original. |
|
|
93
94
|
| `concurrency` | `number` | `0` | Native worker threads. `0` = number of logical CPUs. |
|
|
94
|
-
| `chunkSize` | `number` | `0` | Max source bytes buffered per native compression batch. `0` = one batch for the whole build. A positive value (e.g. `64 * 1024 * 1024`) caps the plugin's peak memory overhead at roughly one batch of source copies plus its compressed outputs; a single file larger than `chunkSize` still forms its own batch. The bundler keeps the original bundle in memory regardless. |
|
|
95
|
+
| `chunkSize` | `number` | `0` | Max source bytes buffered per native compression batch. `0` = one batch for the whole build. A positive value (e.g. `64 * 1024 * 1024`) caps the plugin's peak memory overhead at roughly one batch of source copies plus its compressed outputs; a single file larger than `chunkSize` still forms its own batch. The bundler keeps the original bundle in memory regardless. In [stream mode](#stream-mode) `0` falls back to a 4 MB batch instead of one big batch. |
|
|
96
|
+
| `stream` | `boolean` | `false` | Compress from disk in `writeBundle` (order `post`) instead of in memory in `generateBundle`: files are read on demand in bounded batches (`chunkSize` bytes, default 4 MB), and assets written to disk by other plugins' `writeBundle` hooks are compressed too (see [stream mode](#stream-mode)). |
|
|
95
97
|
| `logLevel` | `'silent' \| 'error' \| 'warn' \| 'info'` | `'info'` | Plugin log verbosity; `info` prints a per-algorithm summary at build end. |
|
|
96
98
|
| `enableInWatchMode` | `boolean` | `false` | The plugin is a no-op in watch/dev mode unless enabled (see [watch mode](#watch--dev-mode)). |
|
|
97
99
|
|
|
@@ -120,7 +122,23 @@ defineAlgorithm('zstd', { level: 12 })
|
|
|
120
122
|
- A failing task never aborts the batch: per-task errors are aggregated and fail the build with one message.
|
|
121
123
|
- Already-compressed artifacts (`.gz`, `.br`, `.zst` — ours or pre-existing) are never re-compressed, so chaining plugin instances can't produce `app.js.gz.br`.
|
|
122
124
|
|
|
123
|
-
Limitation: assets written to disk by other plugins in `writeBundle`/`closeBundle` (i.e. after `generateBundle`) are not seen
|
|
125
|
+
Limitation of the default mode: assets written to disk by other plugins in `writeBundle`/`closeBundle` (i.e. after `generateBundle`) are not seen. This matches how `vite-plugin-compression2` handles the in-bundle pass. Set `stream: true` to remove it.
|
|
126
|
+
|
|
127
|
+
### Stream mode
|
|
128
|
+
|
|
129
|
+
With `stream: true` the plugin skips the in-memory `generateBundle` pass entirely and instead runs at the end of `writeBundle` (hook order `post`), after the bundle — and any extra assets other plugins wrote in their own `writeBundle` hooks — is on disk:
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
compression({
|
|
133
|
+
stream: true,
|
|
134
|
+
chunkSize: 64 * 1024 * 1024, // optional: batch by source bytes instead of by file count
|
|
135
|
+
})
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
- The output directory is scanned recursively and matching files are read **on demand**, never all at once: a batch is flushed to the native module whenever it reaches `chunkSize` source bytes, defaulting to **4 MB** when `chunkSize` is `0`. Peak memory overhead is one batch of sources plus its compressed outputs, regardless of build size.
|
|
139
|
+
- Compressed artifacts are written straight to the output directory (`emitFile` is not available after write); `deleteOriginalAssets` unlinks the originals from disk.
|
|
140
|
+
- The same filter, threshold and re-compression guards apply, and everything already in the output directory that matches them is compressed — including files produced by other plugins after `generateBundle`, the default mode's limitation. Assets written in `closeBundle` (after all `writeBundle` hooks) are still not seen.
|
|
141
|
+
- Trade-off: files the bundler already had in memory are re-read from disk, and per-batch FFI calls replace the single big batch — for small builds the default in-memory mode is faster.
|
|
124
142
|
|
|
125
143
|
### Watch / dev mode
|
|
126
144
|
|
|
@@ -254,7 +272,7 @@ the host, so on an unsupported platform the wasm package must be opted into:
|
|
|
254
272
|
- **No tarball plugin**: out of scope.
|
|
255
273
|
- **gzip default level is 6** (zlib default), not 9 — measurably faster for a ~1% size difference. Pass `defineAlgorithm('gzip', { level: 9 })` to match the reference.
|
|
256
274
|
- **zstd everywhere**: zstd is compiled in, with no dependency on the Node runtime's zstd support (node >= 22.15).
|
|
257
|
-
- Extra options: `concurrency` (native thread cap), `chunkSize` (memory cap per compression batch) and `enableInWatchMode`.
|
|
275
|
+
- Extra options: `concurrency` (native thread cap), `chunkSize` (memory cap per compression batch), `stream` (on-demand disk-based compression in `writeBundle`) and `enableInWatchMode`.
|
|
258
276
|
|
|
259
277
|
## Implementation decisions
|
|
260
278
|
|
package/dist/index.cjs
CHANGED
|
@@ -25,6 +25,7 @@ let node_crypto = require("node:crypto");
|
|
|
25
25
|
let node_path = require("node:path");
|
|
26
26
|
node_path = __toESM(node_path);
|
|
27
27
|
let _rollup_pluginutils = require("@rollup/pluginutils");
|
|
28
|
+
let node_fs_promises = require("node:fs/promises");
|
|
28
29
|
let node_module = require("node:module");
|
|
29
30
|
//#region ts/options.ts
|
|
30
31
|
/**
|
|
@@ -127,7 +128,7 @@ function validateDefined(entry) {
|
|
|
127
128
|
/** Validate and normalize user options. Throws at `compression()` call time. */
|
|
128
129
|
function resolveOptions(options = {}) {
|
|
129
130
|
if (options === null || typeof options !== "object") throw new OptionValidationError("options must be an object");
|
|
130
|
-
const { include = DEFAULT_INCLUDE, exclude, threshold = 0, algorithms = ["gzip", "brotli"], filename, deleteOriginalAssets = false, skipIfLargerOrEqual = true, concurrency = 0, chunkSize = 0, logLevel = "info", enableInWatchMode = false } = options;
|
|
131
|
+
const { include = DEFAULT_INCLUDE, exclude, threshold = 0, algorithms = ["gzip", "brotli"], filename, deleteOriginalAssets = false, skipIfLargerOrEqual = true, concurrency = 0, chunkSize = 0, stream = false, logLevel = "info", enableInWatchMode = false } = options;
|
|
131
132
|
if (typeof threshold !== "number" || Number.isNaN(threshold) || threshold < 0) throw new OptionValidationError(`invalid threshold: expected a non-negative number, got ${JSON.stringify(threshold)}`);
|
|
132
133
|
if (!Number.isInteger(concurrency) || concurrency < 0) throw new OptionValidationError(`invalid concurrency: expected a non-negative integer, got ${JSON.stringify(concurrency)}`);
|
|
133
134
|
if (!Number.isInteger(chunkSize) || chunkSize < 0) throw new OptionValidationError(`invalid chunkSize: expected a non-negative integer number of bytes, got ${JSON.stringify(chunkSize)}`);
|
|
@@ -143,6 +144,7 @@ function resolveOptions(options = {}) {
|
|
|
143
144
|
skipIfLargerOrEqual: Boolean(skipIfLargerOrEqual),
|
|
144
145
|
concurrency,
|
|
145
146
|
chunkSize,
|
|
147
|
+
stream: Boolean(stream),
|
|
146
148
|
logLevel,
|
|
147
149
|
enableInWatchMode: Boolean(enableInWatchMode)
|
|
148
150
|
};
|
|
@@ -167,7 +169,28 @@ function resolveOutputFileName(filename, fileName, algorithm, source) {
|
|
|
167
169
|
const compressBuffers = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("../index.js").compressBuffers;
|
|
168
170
|
//#endregion
|
|
169
171
|
//#region ts/plugin.ts
|
|
172
|
+
/**
|
|
173
|
+
* Rolldown plugin implementation.
|
|
174
|
+
*
|
|
175
|
+
* Default mode: all eligible assets of a build are collected in
|
|
176
|
+
* `generateBundle` (while they are still in memory) and compressed in
|
|
177
|
+
* batched FFI calls; the native module fans the work out across a rayon
|
|
178
|
+
* thread pool without ever blocking the JS event loop. By default
|
|
179
|
+
* everything goes out in a single batch; a positive `chunkSize` flushes a
|
|
180
|
+
* batch whenever its source bytes reach that limit, so only one batch of
|
|
181
|
+
* buffer copies is alive at a time.
|
|
182
|
+
*
|
|
183
|
+
* Stream mode (`stream: true`): compression instead runs at the end of
|
|
184
|
+
* `writeBundle` (order `'post'`), scanning the output directory on disk.
|
|
185
|
+
* Files are read on demand and processed in bounded batches — `chunkSize`
|
|
186
|
+
* source bytes per batch, falling back to
|
|
187
|
+
* {@link STREAM_DEFAULT_CHUNK_SIZE} when `chunkSize` is 0 — so the whole
|
|
188
|
+
* build is never held in memory and assets written to disk by other
|
|
189
|
+
* plugins' `writeBundle` hooks are compressed as well.
|
|
190
|
+
*/
|
|
170
191
|
const PLUGIN_NAME = "rolldown-compression";
|
|
192
|
+
/** Source bytes per batch in stream mode when `chunkSize` is 0. */
|
|
193
|
+
const STREAM_DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
|
|
171
194
|
const LOG_PRIORITY = {
|
|
172
195
|
silent: 0,
|
|
173
196
|
error: 1,
|
|
@@ -197,97 +220,175 @@ function formatBytes(bytes) {
|
|
|
197
220
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
|
|
198
221
|
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
199
222
|
}
|
|
223
|
+
/**
|
|
224
|
+
* Shared batching core: queues per-algorithm tasks, flushes them to the
|
|
225
|
+
* native module and hands successful results to `emit`. Only one batch of
|
|
226
|
+
* source buffers is referenced at a time once a flush trigger is set.
|
|
227
|
+
*/
|
|
228
|
+
function createBatchRunner(options, logger, emittedNames, emit, fail) {
|
|
229
|
+
const processedSources = /* @__PURE__ */ new Set();
|
|
230
|
+
const emittedBySource = /* @__PURE__ */ new Map();
|
|
231
|
+
const failures = [];
|
|
232
|
+
const stats = /* @__PURE__ */ new Map();
|
|
233
|
+
const chunkSize = options.chunkSize > 0 ? options.chunkSize : options.stream ? STREAM_DEFAULT_CHUNK_SIZE : 0;
|
|
234
|
+
let pending = [];
|
|
235
|
+
let pendingSourceBytes = 0;
|
|
236
|
+
const flush = async () => {
|
|
237
|
+
if (pending.length === 0) return;
|
|
238
|
+
const batch = pending;
|
|
239
|
+
pending = [];
|
|
240
|
+
pendingSourceBytes = 0;
|
|
241
|
+
const results = await compressBuffers(batch.map((artifact) => artifact.task), batch.map((artifact) => artifact.buffer), {
|
|
242
|
+
concurrency: options.concurrency,
|
|
243
|
+
skipIfLargerOrEqual: options.skipIfLargerOrEqual
|
|
244
|
+
});
|
|
245
|
+
for (const [index, result] of results.entries()) {
|
|
246
|
+
const artifact = batch[index];
|
|
247
|
+
if (artifact === void 0) continue;
|
|
248
|
+
if (result.error !== void 0 && result.error !== null) {
|
|
249
|
+
failures.push(`${result.fileName} (${result.algorithm}): ${result.error}`);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
if (result.skipped) {
|
|
253
|
+
logger.info(`skipped ${artifact.outputFileName}: ${result.algorithm} output would not be smaller than the original`);
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
await emit(artifact, result.data);
|
|
257
|
+
emittedNames.add(artifact.outputFileName);
|
|
258
|
+
emittedBySource.set(artifact.sourceFileName, (emittedBySource.get(artifact.sourceFileName) ?? 0) + 1);
|
|
259
|
+
const stat = stats.get(result.algorithm) ?? {
|
|
260
|
+
count: 0,
|
|
261
|
+
originalBytes: 0,
|
|
262
|
+
outputBytes: 0
|
|
263
|
+
};
|
|
264
|
+
stat.count += 1;
|
|
265
|
+
stat.originalBytes += result.originalSize;
|
|
266
|
+
stat.outputBytes += result.compressedSize;
|
|
267
|
+
stats.set(result.algorithm, stat);
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
const addFile = async (fileName, buffer) => {
|
|
271
|
+
for (const algorithm of options.algorithms) {
|
|
272
|
+
const outputFileName = resolveOutputFileName(options.filename, fileName, algorithm, buffer);
|
|
273
|
+
if (outputFileName === fileName) fail(`the filename option resolved "${fileName}" (${algorithm.algorithm}) to the same name as the source asset; refusing to overwrite it`);
|
|
274
|
+
pending.push({
|
|
275
|
+
task: {
|
|
276
|
+
fileName,
|
|
277
|
+
algorithm: algorithm.algorithm,
|
|
278
|
+
level: algorithm.level,
|
|
279
|
+
windowBits: algorithm.windowBits
|
|
280
|
+
},
|
|
281
|
+
buffer,
|
|
282
|
+
sourceFileName: fileName,
|
|
283
|
+
outputFileName
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
processedSources.add(fileName);
|
|
287
|
+
pendingSourceBytes += buffer.byteLength;
|
|
288
|
+
if (chunkSize > 0 && pendingSourceBytes >= chunkSize) await flush();
|
|
289
|
+
};
|
|
290
|
+
return {
|
|
291
|
+
addFile,
|
|
292
|
+
flush,
|
|
293
|
+
processedSources,
|
|
294
|
+
emittedBySource,
|
|
295
|
+
failures,
|
|
296
|
+
stats
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function logSummary(logger, stats, startedAt) {
|
|
300
|
+
const summary = [...stats.entries()].map(([algorithm, stat]) => `${algorithm}: ${stat.count} file(s), ${formatBytes(stat.originalBytes)} -> ${formatBytes(stat.outputBytes)}`).join("; ");
|
|
301
|
+
if (summary.length === 0) return;
|
|
302
|
+
const totalSaved = [...stats.values()].reduce((sum, stat) => sum + (stat.originalBytes - stat.outputBytes), 0);
|
|
303
|
+
const elapsedMs = performance.now() - startedAt;
|
|
304
|
+
logger.info(`${summary}; saved ${formatBytes(totalSaved)} in ${(elapsedMs / 1e3).toFixed(2)}s`);
|
|
305
|
+
}
|
|
306
|
+
/** Recursively list every file under `root`, in a deterministic order. */
|
|
307
|
+
async function walkFiles(root) {
|
|
308
|
+
const files = [];
|
|
309
|
+
const visit = async (dir) => {
|
|
310
|
+
const entries = await (0, node_fs_promises.readdir)(dir, { withFileTypes: true });
|
|
311
|
+
entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
312
|
+
for (const entry of entries) {
|
|
313
|
+
const absolute = node_path.default.join(dir, entry.name);
|
|
314
|
+
if (entry.isDirectory()) await visit(absolute);
|
|
315
|
+
else if (entry.isFile()) files.push(absolute);
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
await visit(root);
|
|
319
|
+
return files;
|
|
320
|
+
}
|
|
200
321
|
function createCompressionPlugin(options) {
|
|
201
322
|
const logger = createLogger(options.logLevel);
|
|
202
323
|
const emittedNames = /* @__PURE__ */ new Set();
|
|
203
324
|
return Object.assign({
|
|
204
325
|
name: PLUGIN_NAME,
|
|
205
326
|
async generateBundle(_outputOptions, bundle) {
|
|
327
|
+
if (options.stream) return;
|
|
206
328
|
if (this.meta?.watchMode && !options.enableInWatchMode) {
|
|
207
329
|
logger.info("watch mode detected, skipping compression (set enableInWatchMode to opt in)");
|
|
208
330
|
return;
|
|
209
331
|
}
|
|
210
332
|
const startedAt = performance.now();
|
|
211
|
-
const
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
const flush = async () => {
|
|
218
|
-
if (pending.length === 0) return;
|
|
219
|
-
const batch = pending;
|
|
220
|
-
pending = [];
|
|
221
|
-
pendingSourceBytes = 0;
|
|
222
|
-
const results = await compressBuffers(batch.map((artifact) => artifact.task), batch.map((artifact) => artifact.buffer), {
|
|
223
|
-
concurrency: options.concurrency,
|
|
224
|
-
skipIfLargerOrEqual: options.skipIfLargerOrEqual
|
|
333
|
+
const fail = (message) => this.error(/* @__PURE__ */ new Error(`[${PLUGIN_NAME}] ${message}`));
|
|
334
|
+
const runner = createBatchRunner(options, logger, emittedNames, (artifact, data) => {
|
|
335
|
+
this.emitFile({
|
|
336
|
+
type: "asset",
|
|
337
|
+
fileName: artifact.outputFileName,
|
|
338
|
+
source: data
|
|
225
339
|
});
|
|
226
|
-
|
|
227
|
-
const artifact = batch[index];
|
|
228
|
-
if (artifact === void 0) continue;
|
|
229
|
-
if (result.error !== void 0 && result.error !== null) {
|
|
230
|
-
failures.push(`${result.fileName} (${result.algorithm}): ${result.error}`);
|
|
231
|
-
continue;
|
|
232
|
-
}
|
|
233
|
-
if (result.skipped) {
|
|
234
|
-
logger.info(`skipped ${artifact.outputFileName}: ${result.algorithm} output would not be smaller than the original`);
|
|
235
|
-
continue;
|
|
236
|
-
}
|
|
237
|
-
this.emitFile({
|
|
238
|
-
type: "asset",
|
|
239
|
-
fileName: artifact.outputFileName,
|
|
240
|
-
source: result.data
|
|
241
|
-
});
|
|
242
|
-
emittedNames.add(artifact.outputFileName);
|
|
243
|
-
emittedBySource.set(artifact.sourceFileName, (emittedBySource.get(artifact.sourceFileName) ?? 0) + 1);
|
|
244
|
-
const stat = stats.get(result.algorithm) ?? {
|
|
245
|
-
count: 0,
|
|
246
|
-
originalBytes: 0,
|
|
247
|
-
outputBytes: 0
|
|
248
|
-
};
|
|
249
|
-
stat.count += 1;
|
|
250
|
-
stat.originalBytes += result.originalSize;
|
|
251
|
-
stat.outputBytes += result.compressedSize;
|
|
252
|
-
stats.set(result.algorithm, stat);
|
|
253
|
-
}
|
|
254
|
-
};
|
|
340
|
+
}, fail);
|
|
255
341
|
for (const [fileName, output] of Object.entries(bundle)) {
|
|
256
342
|
if (!options.filter(fileName)) continue;
|
|
257
343
|
if (COMPRESSED_EXTENSION_RE.test(fileName) || emittedNames.has(fileName)) continue;
|
|
258
344
|
const buffer = toBuffer(output.type === "chunk" ? output.code : output.source);
|
|
259
345
|
if (buffer.byteLength < options.threshold) continue;
|
|
260
|
-
|
|
261
|
-
const outputFileName = resolveOutputFileName(options.filename, fileName, algorithm, buffer);
|
|
262
|
-
if (outputFileName === fileName) this.error(/* @__PURE__ */ new Error(`[${PLUGIN_NAME}] the filename option resolved "${fileName}" (${algorithm.algorithm}) to the same name as the source asset; refusing to overwrite it`));
|
|
263
|
-
pending.push({
|
|
264
|
-
task: {
|
|
265
|
-
fileName,
|
|
266
|
-
algorithm: algorithm.algorithm,
|
|
267
|
-
level: algorithm.level,
|
|
268
|
-
windowBits: algorithm.windowBits
|
|
269
|
-
},
|
|
270
|
-
buffer,
|
|
271
|
-
sourceFileName: fileName,
|
|
272
|
-
outputFileName
|
|
273
|
-
});
|
|
274
|
-
}
|
|
275
|
-
processedSources.add(fileName);
|
|
276
|
-
pendingSourceBytes += buffer.byteLength;
|
|
277
|
-
if (options.chunkSize > 0 && pendingSourceBytes >= options.chunkSize) await flush();
|
|
346
|
+
await runner.addFile(fileName, buffer);
|
|
278
347
|
}
|
|
279
|
-
await flush();
|
|
280
|
-
if (processedSources.size === 0) return;
|
|
281
|
-
if (failures.length > 0)
|
|
282
|
-
if (options.deleteOriginalAssets) for (const fileName of processedSources) {
|
|
283
|
-
if ((emittedBySource.get(fileName) ?? 0) === 0) logger.warn(`deleteOriginalAssets removed "${fileName}" even though no compressed variant was emitted for it`);
|
|
348
|
+
await runner.flush();
|
|
349
|
+
if (runner.processedSources.size === 0) return;
|
|
350
|
+
if (runner.failures.length > 0) fail(`${runner.failures.length} compression task(s) failed:\n${runner.failures.join("\n")}`);
|
|
351
|
+
if (options.deleteOriginalAssets) for (const fileName of runner.processedSources) {
|
|
352
|
+
if ((runner.emittedBySource.get(fileName) ?? 0) === 0) logger.warn(`deleteOriginalAssets removed "${fileName}" even though no compressed variant was emitted for it`);
|
|
284
353
|
delete bundle[fileName];
|
|
285
354
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
355
|
+
logSummary(logger, runner.stats, startedAt);
|
|
356
|
+
},
|
|
357
|
+
writeBundle: {
|
|
358
|
+
order: "post",
|
|
359
|
+
async handler(outputOptions) {
|
|
360
|
+
if (!options.stream) return;
|
|
361
|
+
if (this.meta?.watchMode && !options.enableInWatchMode) {
|
|
362
|
+
logger.info("watch mode detected, skipping compression (set enableInWatchMode to opt in)");
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const outDir = outputOptions.dir !== void 0 ? node_path.default.resolve(outputOptions.dir) : outputOptions.file !== void 0 ? node_path.default.resolve(node_path.default.dirname(outputOptions.file)) : void 0;
|
|
366
|
+
if (outDir === void 0) {
|
|
367
|
+
logger.warn("stream mode could not determine the output directory, skipping compression");
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
const startedAt = performance.now();
|
|
371
|
+
const fail = (message) => this.error(/* @__PURE__ */ new Error(`[${PLUGIN_NAME}] ${message}`));
|
|
372
|
+
const runner = createBatchRunner(options, logger, emittedNames, async (artifact, data) => {
|
|
373
|
+
const target = node_path.default.join(outDir, artifact.outputFileName);
|
|
374
|
+
await (0, node_fs_promises.mkdir)(node_path.default.dirname(target), { recursive: true });
|
|
375
|
+
await (0, node_fs_promises.writeFile)(target, data);
|
|
376
|
+
}, fail);
|
|
377
|
+
for (const absolute of await walkFiles(outDir)) {
|
|
378
|
+
const fileName = node_path.default.relative(outDir, absolute).split(node_path.default.sep).join("/");
|
|
379
|
+
if (!options.filter(fileName)) continue;
|
|
380
|
+
if (COMPRESSED_EXTENSION_RE.test(fileName) || emittedNames.has(fileName)) continue;
|
|
381
|
+
if ((await (0, node_fs_promises.stat)(absolute)).size < options.threshold) continue;
|
|
382
|
+
await runner.addFile(fileName, await (0, node_fs_promises.readFile)(absolute));
|
|
383
|
+
}
|
|
384
|
+
await runner.flush();
|
|
385
|
+
if (runner.processedSources.size === 0) return;
|
|
386
|
+
if (runner.failures.length > 0) fail(`${runner.failures.length} compression task(s) failed:\n${runner.failures.join("\n")}`);
|
|
387
|
+
if (options.deleteOriginalAssets) for (const fileName of runner.processedSources) {
|
|
388
|
+
if ((runner.emittedBySource.get(fileName) ?? 0) === 0) logger.warn(`deleteOriginalAssets removed "${fileName}" even though no compressed variant was emitted for it`);
|
|
389
|
+
await (0, node_fs_promises.unlink)(node_path.default.join(outDir, fileName));
|
|
390
|
+
}
|
|
391
|
+
logSummary(logger, runner.stats, startedAt);
|
|
291
392
|
}
|
|
292
393
|
}
|
|
293
394
|
}, { apply: "build" });
|
package/dist/index.d.cts
CHANGED
|
@@ -79,6 +79,16 @@ interface CompressionOptions {
|
|
|
79
79
|
* @default 0
|
|
80
80
|
*/
|
|
81
81
|
chunkSize?: number;
|
|
82
|
+
/**
|
|
83
|
+
* Compress from disk at the end of `writeBundle` instead of in memory in
|
|
84
|
+
* `generateBundle`. The output directory is scanned and files are read on
|
|
85
|
+
* demand in bounded batches (`chunkSize` source bytes per batch, or 4 MB
|
|
86
|
+
* per batch when `chunkSize` is 0), so the whole build is never held in
|
|
87
|
+
* memory and assets written to disk by other plugins' `writeBundle`
|
|
88
|
+
* hooks are picked up as well.
|
|
89
|
+
* @default false
|
|
90
|
+
*/
|
|
91
|
+
stream?: boolean;
|
|
82
92
|
/** @default 'info' */
|
|
83
93
|
logLevel?: LogLevel;
|
|
84
94
|
/**
|
package/dist/index.d.mts
CHANGED
|
@@ -79,6 +79,16 @@ interface CompressionOptions {
|
|
|
79
79
|
* @default 0
|
|
80
80
|
*/
|
|
81
81
|
chunkSize?: number;
|
|
82
|
+
/**
|
|
83
|
+
* Compress from disk at the end of `writeBundle` instead of in memory in
|
|
84
|
+
* `generateBundle`. The output directory is scanned and files are read on
|
|
85
|
+
* demand in bounded batches (`chunkSize` source bytes per batch, or 4 MB
|
|
86
|
+
* per batch when `chunkSize` is 0), so the whole build is never held in
|
|
87
|
+
* memory and assets written to disk by other plugins' `writeBundle`
|
|
88
|
+
* hooks are picked up as well.
|
|
89
|
+
* @default false
|
|
90
|
+
*/
|
|
91
|
+
stream?: boolean;
|
|
82
92
|
/** @default 'info' */
|
|
83
93
|
logLevel?: LogLevel;
|
|
84
94
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { createRequire } from "node:module";
|
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { createFilter } from "@rollup/pluginutils";
|
|
5
|
+
import { mkdir, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
5
6
|
//#region ts/options.ts
|
|
6
7
|
/**
|
|
7
8
|
* Option types, normalization and validation for the public API.
|
|
@@ -103,7 +104,7 @@ function validateDefined(entry) {
|
|
|
103
104
|
/** Validate and normalize user options. Throws at `compression()` call time. */
|
|
104
105
|
function resolveOptions(options = {}) {
|
|
105
106
|
if (options === null || typeof options !== "object") throw new OptionValidationError("options must be an object");
|
|
106
|
-
const { include = DEFAULT_INCLUDE, exclude, threshold = 0, algorithms = ["gzip", "brotli"], filename, deleteOriginalAssets = false, skipIfLargerOrEqual = true, concurrency = 0, chunkSize = 0, logLevel = "info", enableInWatchMode = false } = options;
|
|
107
|
+
const { include = DEFAULT_INCLUDE, exclude, threshold = 0, algorithms = ["gzip", "brotli"], filename, deleteOriginalAssets = false, skipIfLargerOrEqual = true, concurrency = 0, chunkSize = 0, stream = false, logLevel = "info", enableInWatchMode = false } = options;
|
|
107
108
|
if (typeof threshold !== "number" || Number.isNaN(threshold) || threshold < 0) throw new OptionValidationError(`invalid threshold: expected a non-negative number, got ${JSON.stringify(threshold)}`);
|
|
108
109
|
if (!Number.isInteger(concurrency) || concurrency < 0) throw new OptionValidationError(`invalid concurrency: expected a non-negative integer, got ${JSON.stringify(concurrency)}`);
|
|
109
110
|
if (!Number.isInteger(chunkSize) || chunkSize < 0) throw new OptionValidationError(`invalid chunkSize: expected a non-negative integer number of bytes, got ${JSON.stringify(chunkSize)}`);
|
|
@@ -119,6 +120,7 @@ function resolveOptions(options = {}) {
|
|
|
119
120
|
skipIfLargerOrEqual: Boolean(skipIfLargerOrEqual),
|
|
120
121
|
concurrency,
|
|
121
122
|
chunkSize,
|
|
123
|
+
stream: Boolean(stream),
|
|
122
124
|
logLevel,
|
|
123
125
|
enableInWatchMode: Boolean(enableInWatchMode)
|
|
124
126
|
};
|
|
@@ -143,7 +145,28 @@ function resolveOutputFileName(filename, fileName, algorithm, source) {
|
|
|
143
145
|
const compressBuffers = createRequire(import.meta.url)("../index.js").compressBuffers;
|
|
144
146
|
//#endregion
|
|
145
147
|
//#region ts/plugin.ts
|
|
148
|
+
/**
|
|
149
|
+
* Rolldown plugin implementation.
|
|
150
|
+
*
|
|
151
|
+
* Default mode: all eligible assets of a build are collected in
|
|
152
|
+
* `generateBundle` (while they are still in memory) and compressed in
|
|
153
|
+
* batched FFI calls; the native module fans the work out across a rayon
|
|
154
|
+
* thread pool without ever blocking the JS event loop. By default
|
|
155
|
+
* everything goes out in a single batch; a positive `chunkSize` flushes a
|
|
156
|
+
* batch whenever its source bytes reach that limit, so only one batch of
|
|
157
|
+
* buffer copies is alive at a time.
|
|
158
|
+
*
|
|
159
|
+
* Stream mode (`stream: true`): compression instead runs at the end of
|
|
160
|
+
* `writeBundle` (order `'post'`), scanning the output directory on disk.
|
|
161
|
+
* Files are read on demand and processed in bounded batches — `chunkSize`
|
|
162
|
+
* source bytes per batch, falling back to
|
|
163
|
+
* {@link STREAM_DEFAULT_CHUNK_SIZE} when `chunkSize` is 0 — so the whole
|
|
164
|
+
* build is never held in memory and assets written to disk by other
|
|
165
|
+
* plugins' `writeBundle` hooks are compressed as well.
|
|
166
|
+
*/
|
|
146
167
|
const PLUGIN_NAME = "rolldown-compression";
|
|
168
|
+
/** Source bytes per batch in stream mode when `chunkSize` is 0. */
|
|
169
|
+
const STREAM_DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024;
|
|
147
170
|
const LOG_PRIORITY = {
|
|
148
171
|
silent: 0,
|
|
149
172
|
error: 1,
|
|
@@ -173,97 +196,175 @@ function formatBytes(bytes) {
|
|
|
173
196
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
|
|
174
197
|
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
175
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* Shared batching core: queues per-algorithm tasks, flushes them to the
|
|
201
|
+
* native module and hands successful results to `emit`. Only one batch of
|
|
202
|
+
* source buffers is referenced at a time once a flush trigger is set.
|
|
203
|
+
*/
|
|
204
|
+
function createBatchRunner(options, logger, emittedNames, emit, fail) {
|
|
205
|
+
const processedSources = /* @__PURE__ */ new Set();
|
|
206
|
+
const emittedBySource = /* @__PURE__ */ new Map();
|
|
207
|
+
const failures = [];
|
|
208
|
+
const stats = /* @__PURE__ */ new Map();
|
|
209
|
+
const chunkSize = options.chunkSize > 0 ? options.chunkSize : options.stream ? STREAM_DEFAULT_CHUNK_SIZE : 0;
|
|
210
|
+
let pending = [];
|
|
211
|
+
let pendingSourceBytes = 0;
|
|
212
|
+
const flush = async () => {
|
|
213
|
+
if (pending.length === 0) return;
|
|
214
|
+
const batch = pending;
|
|
215
|
+
pending = [];
|
|
216
|
+
pendingSourceBytes = 0;
|
|
217
|
+
const results = await compressBuffers(batch.map((artifact) => artifact.task), batch.map((artifact) => artifact.buffer), {
|
|
218
|
+
concurrency: options.concurrency,
|
|
219
|
+
skipIfLargerOrEqual: options.skipIfLargerOrEqual
|
|
220
|
+
});
|
|
221
|
+
for (const [index, result] of results.entries()) {
|
|
222
|
+
const artifact = batch[index];
|
|
223
|
+
if (artifact === void 0) continue;
|
|
224
|
+
if (result.error !== void 0 && result.error !== null) {
|
|
225
|
+
failures.push(`${result.fileName} (${result.algorithm}): ${result.error}`);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (result.skipped) {
|
|
229
|
+
logger.info(`skipped ${artifact.outputFileName}: ${result.algorithm} output would not be smaller than the original`);
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
await emit(artifact, result.data);
|
|
233
|
+
emittedNames.add(artifact.outputFileName);
|
|
234
|
+
emittedBySource.set(artifact.sourceFileName, (emittedBySource.get(artifact.sourceFileName) ?? 0) + 1);
|
|
235
|
+
const stat = stats.get(result.algorithm) ?? {
|
|
236
|
+
count: 0,
|
|
237
|
+
originalBytes: 0,
|
|
238
|
+
outputBytes: 0
|
|
239
|
+
};
|
|
240
|
+
stat.count += 1;
|
|
241
|
+
stat.originalBytes += result.originalSize;
|
|
242
|
+
stat.outputBytes += result.compressedSize;
|
|
243
|
+
stats.set(result.algorithm, stat);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
const addFile = async (fileName, buffer) => {
|
|
247
|
+
for (const algorithm of options.algorithms) {
|
|
248
|
+
const outputFileName = resolveOutputFileName(options.filename, fileName, algorithm, buffer);
|
|
249
|
+
if (outputFileName === fileName) fail(`the filename option resolved "${fileName}" (${algorithm.algorithm}) to the same name as the source asset; refusing to overwrite it`);
|
|
250
|
+
pending.push({
|
|
251
|
+
task: {
|
|
252
|
+
fileName,
|
|
253
|
+
algorithm: algorithm.algorithm,
|
|
254
|
+
level: algorithm.level,
|
|
255
|
+
windowBits: algorithm.windowBits
|
|
256
|
+
},
|
|
257
|
+
buffer,
|
|
258
|
+
sourceFileName: fileName,
|
|
259
|
+
outputFileName
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
processedSources.add(fileName);
|
|
263
|
+
pendingSourceBytes += buffer.byteLength;
|
|
264
|
+
if (chunkSize > 0 && pendingSourceBytes >= chunkSize) await flush();
|
|
265
|
+
};
|
|
266
|
+
return {
|
|
267
|
+
addFile,
|
|
268
|
+
flush,
|
|
269
|
+
processedSources,
|
|
270
|
+
emittedBySource,
|
|
271
|
+
failures,
|
|
272
|
+
stats
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function logSummary(logger, stats, startedAt) {
|
|
276
|
+
const summary = [...stats.entries()].map(([algorithm, stat]) => `${algorithm}: ${stat.count} file(s), ${formatBytes(stat.originalBytes)} -> ${formatBytes(stat.outputBytes)}`).join("; ");
|
|
277
|
+
if (summary.length === 0) return;
|
|
278
|
+
const totalSaved = [...stats.values()].reduce((sum, stat) => sum + (stat.originalBytes - stat.outputBytes), 0);
|
|
279
|
+
const elapsedMs = performance.now() - startedAt;
|
|
280
|
+
logger.info(`${summary}; saved ${formatBytes(totalSaved)} in ${(elapsedMs / 1e3).toFixed(2)}s`);
|
|
281
|
+
}
|
|
282
|
+
/** Recursively list every file under `root`, in a deterministic order. */
|
|
283
|
+
async function walkFiles(root) {
|
|
284
|
+
const files = [];
|
|
285
|
+
const visit = async (dir) => {
|
|
286
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
287
|
+
entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
288
|
+
for (const entry of entries) {
|
|
289
|
+
const absolute = path.join(dir, entry.name);
|
|
290
|
+
if (entry.isDirectory()) await visit(absolute);
|
|
291
|
+
else if (entry.isFile()) files.push(absolute);
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
await visit(root);
|
|
295
|
+
return files;
|
|
296
|
+
}
|
|
176
297
|
function createCompressionPlugin(options) {
|
|
177
298
|
const logger = createLogger(options.logLevel);
|
|
178
299
|
const emittedNames = /* @__PURE__ */ new Set();
|
|
179
300
|
return Object.assign({
|
|
180
301
|
name: PLUGIN_NAME,
|
|
181
302
|
async generateBundle(_outputOptions, bundle) {
|
|
303
|
+
if (options.stream) return;
|
|
182
304
|
if (this.meta?.watchMode && !options.enableInWatchMode) {
|
|
183
305
|
logger.info("watch mode detected, skipping compression (set enableInWatchMode to opt in)");
|
|
184
306
|
return;
|
|
185
307
|
}
|
|
186
308
|
const startedAt = performance.now();
|
|
187
|
-
const
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
const flush = async () => {
|
|
194
|
-
if (pending.length === 0) return;
|
|
195
|
-
const batch = pending;
|
|
196
|
-
pending = [];
|
|
197
|
-
pendingSourceBytes = 0;
|
|
198
|
-
const results = await compressBuffers(batch.map((artifact) => artifact.task), batch.map((artifact) => artifact.buffer), {
|
|
199
|
-
concurrency: options.concurrency,
|
|
200
|
-
skipIfLargerOrEqual: options.skipIfLargerOrEqual
|
|
309
|
+
const fail = (message) => this.error(/* @__PURE__ */ new Error(`[${PLUGIN_NAME}] ${message}`));
|
|
310
|
+
const runner = createBatchRunner(options, logger, emittedNames, (artifact, data) => {
|
|
311
|
+
this.emitFile({
|
|
312
|
+
type: "asset",
|
|
313
|
+
fileName: artifact.outputFileName,
|
|
314
|
+
source: data
|
|
201
315
|
});
|
|
202
|
-
|
|
203
|
-
const artifact = batch[index];
|
|
204
|
-
if (artifact === void 0) continue;
|
|
205
|
-
if (result.error !== void 0 && result.error !== null) {
|
|
206
|
-
failures.push(`${result.fileName} (${result.algorithm}): ${result.error}`);
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
if (result.skipped) {
|
|
210
|
-
logger.info(`skipped ${artifact.outputFileName}: ${result.algorithm} output would not be smaller than the original`);
|
|
211
|
-
continue;
|
|
212
|
-
}
|
|
213
|
-
this.emitFile({
|
|
214
|
-
type: "asset",
|
|
215
|
-
fileName: artifact.outputFileName,
|
|
216
|
-
source: result.data
|
|
217
|
-
});
|
|
218
|
-
emittedNames.add(artifact.outputFileName);
|
|
219
|
-
emittedBySource.set(artifact.sourceFileName, (emittedBySource.get(artifact.sourceFileName) ?? 0) + 1);
|
|
220
|
-
const stat = stats.get(result.algorithm) ?? {
|
|
221
|
-
count: 0,
|
|
222
|
-
originalBytes: 0,
|
|
223
|
-
outputBytes: 0
|
|
224
|
-
};
|
|
225
|
-
stat.count += 1;
|
|
226
|
-
stat.originalBytes += result.originalSize;
|
|
227
|
-
stat.outputBytes += result.compressedSize;
|
|
228
|
-
stats.set(result.algorithm, stat);
|
|
229
|
-
}
|
|
230
|
-
};
|
|
316
|
+
}, fail);
|
|
231
317
|
for (const [fileName, output] of Object.entries(bundle)) {
|
|
232
318
|
if (!options.filter(fileName)) continue;
|
|
233
319
|
if (COMPRESSED_EXTENSION_RE.test(fileName) || emittedNames.has(fileName)) continue;
|
|
234
320
|
const buffer = toBuffer(output.type === "chunk" ? output.code : output.source);
|
|
235
321
|
if (buffer.byteLength < options.threshold) continue;
|
|
236
|
-
|
|
237
|
-
const outputFileName = resolveOutputFileName(options.filename, fileName, algorithm, buffer);
|
|
238
|
-
if (outputFileName === fileName) this.error(/* @__PURE__ */ new Error(`[${PLUGIN_NAME}] the filename option resolved "${fileName}" (${algorithm.algorithm}) to the same name as the source asset; refusing to overwrite it`));
|
|
239
|
-
pending.push({
|
|
240
|
-
task: {
|
|
241
|
-
fileName,
|
|
242
|
-
algorithm: algorithm.algorithm,
|
|
243
|
-
level: algorithm.level,
|
|
244
|
-
windowBits: algorithm.windowBits
|
|
245
|
-
},
|
|
246
|
-
buffer,
|
|
247
|
-
sourceFileName: fileName,
|
|
248
|
-
outputFileName
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
processedSources.add(fileName);
|
|
252
|
-
pendingSourceBytes += buffer.byteLength;
|
|
253
|
-
if (options.chunkSize > 0 && pendingSourceBytes >= options.chunkSize) await flush();
|
|
322
|
+
await runner.addFile(fileName, buffer);
|
|
254
323
|
}
|
|
255
|
-
await flush();
|
|
256
|
-
if (processedSources.size === 0) return;
|
|
257
|
-
if (failures.length > 0)
|
|
258
|
-
if (options.deleteOriginalAssets) for (const fileName of processedSources) {
|
|
259
|
-
if ((emittedBySource.get(fileName) ?? 0) === 0) logger.warn(`deleteOriginalAssets removed "${fileName}" even though no compressed variant was emitted for it`);
|
|
324
|
+
await runner.flush();
|
|
325
|
+
if (runner.processedSources.size === 0) return;
|
|
326
|
+
if (runner.failures.length > 0) fail(`${runner.failures.length} compression task(s) failed:\n${runner.failures.join("\n")}`);
|
|
327
|
+
if (options.deleteOriginalAssets) for (const fileName of runner.processedSources) {
|
|
328
|
+
if ((runner.emittedBySource.get(fileName) ?? 0) === 0) logger.warn(`deleteOriginalAssets removed "${fileName}" even though no compressed variant was emitted for it`);
|
|
260
329
|
delete bundle[fileName];
|
|
261
330
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
331
|
+
logSummary(logger, runner.stats, startedAt);
|
|
332
|
+
},
|
|
333
|
+
writeBundle: {
|
|
334
|
+
order: "post",
|
|
335
|
+
async handler(outputOptions) {
|
|
336
|
+
if (!options.stream) return;
|
|
337
|
+
if (this.meta?.watchMode && !options.enableInWatchMode) {
|
|
338
|
+
logger.info("watch mode detected, skipping compression (set enableInWatchMode to opt in)");
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
const outDir = outputOptions.dir !== void 0 ? path.resolve(outputOptions.dir) : outputOptions.file !== void 0 ? path.resolve(path.dirname(outputOptions.file)) : void 0;
|
|
342
|
+
if (outDir === void 0) {
|
|
343
|
+
logger.warn("stream mode could not determine the output directory, skipping compression");
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const startedAt = performance.now();
|
|
347
|
+
const fail = (message) => this.error(/* @__PURE__ */ new Error(`[${PLUGIN_NAME}] ${message}`));
|
|
348
|
+
const runner = createBatchRunner(options, logger, emittedNames, async (artifact, data) => {
|
|
349
|
+
const target = path.join(outDir, artifact.outputFileName);
|
|
350
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
351
|
+
await writeFile(target, data);
|
|
352
|
+
}, fail);
|
|
353
|
+
for (const absolute of await walkFiles(outDir)) {
|
|
354
|
+
const fileName = path.relative(outDir, absolute).split(path.sep).join("/");
|
|
355
|
+
if (!options.filter(fileName)) continue;
|
|
356
|
+
if (COMPRESSED_EXTENSION_RE.test(fileName) || emittedNames.has(fileName)) continue;
|
|
357
|
+
if ((await stat(absolute)).size < options.threshold) continue;
|
|
358
|
+
await runner.addFile(fileName, await readFile(absolute));
|
|
359
|
+
}
|
|
360
|
+
await runner.flush();
|
|
361
|
+
if (runner.processedSources.size === 0) return;
|
|
362
|
+
if (runner.failures.length > 0) fail(`${runner.failures.length} compression task(s) failed:\n${runner.failures.join("\n")}`);
|
|
363
|
+
if (options.deleteOriginalAssets) for (const fileName of runner.processedSources) {
|
|
364
|
+
if ((runner.emittedBySource.get(fileName) ?? 0) === 0) logger.warn(`deleteOriginalAssets removed "${fileName}" even though no compressed variant was emitted for it`);
|
|
365
|
+
await unlink(path.join(outDir, fileName));
|
|
366
|
+
}
|
|
367
|
+
logSummary(logger, runner.stats, startedAt);
|
|
267
368
|
}
|
|
268
369
|
}
|
|
269
370
|
}, { apply: "build" });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@medicomind/rolldown-compression",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Fast native (Rust) gzip / brotli / zstd compression plugin for Rolldown, powered by napi-rs",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"rolldown",
|
|
@@ -91,13 +91,13 @@
|
|
|
91
91
|
"rolldown": "^1.0.0"
|
|
92
92
|
},
|
|
93
93
|
"optionalDependencies": {
|
|
94
|
-
"@medicomind/rolldown-compression-darwin-arm64": "1.0
|
|
95
|
-
"@medicomind/rolldown-compression-darwin-x64": "1.0
|
|
96
|
-
"@medicomind/rolldown-compression-linux-arm64-gnu": "1.0
|
|
97
|
-
"@medicomind/rolldown-compression-linux-x64-gnu": "1.0
|
|
98
|
-
"@medicomind/rolldown-compression-linux-x64-musl": "1.0
|
|
99
|
-
"@medicomind/rolldown-compression-wasm32-wasi": "1.0
|
|
100
|
-
"@medicomind/rolldown-compression-win32-x64-msvc": "1.0
|
|
94
|
+
"@medicomind/rolldown-compression-darwin-arm64": "1.1.0",
|
|
95
|
+
"@medicomind/rolldown-compression-darwin-x64": "1.1.0",
|
|
96
|
+
"@medicomind/rolldown-compression-linux-arm64-gnu": "1.1.0",
|
|
97
|
+
"@medicomind/rolldown-compression-linux-x64-gnu": "1.1.0",
|
|
98
|
+
"@medicomind/rolldown-compression-linux-x64-musl": "1.1.0",
|
|
99
|
+
"@medicomind/rolldown-compression-wasm32-wasi": "1.1.0",
|
|
100
|
+
"@medicomind/rolldown-compression-win32-x64-msvc": "1.1.0"
|
|
101
101
|
},
|
|
102
102
|
"devDependencies": {
|
|
103
103
|
"@biomejs/biome": "^2.5.3",
|