arui-scripts 26.0.1 → 26.1.0-persistent-cache-beta-20261103084257

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.
Files changed (59) hide show
  1. package/.prettierignore +1 -0
  2. package/.turbo/turbo-test.log +14 -7
  3. package/CHANGELOG.md +19 -4
  4. package/README.md +3 -0
  5. package/build/bin/commands-registry.js +13 -0
  6. package/build/commands/build/build-wrapper.d.ts +4 -3
  7. package/build/commands/build/build-wrapper.js +64 -28
  8. package/build/commands/build/client.js +20 -19
  9. package/build/commands/bundle-analyze/index.js +2 -0
  10. package/build/commands/cache.d.ts +2 -0
  11. package/build/commands/cache.js +57 -0
  12. package/build/commands/util/cache-diagnostics.d.ts +10 -0
  13. package/build/commands/util/cache-diagnostics.js +154 -0
  14. package/build/commands/util/create-compiler.d.ts +5 -0
  15. package/build/commands/util/create-compiler.js +37 -0
  16. package/build/commands/util/graceful-shutdown.d.ts +6 -0
  17. package/build/commands/util/graceful-shutdown.js +52 -0
  18. package/build/commands/util/rsdoctor-snapshot.js +3 -0
  19. package/build/commands/util/run-client-dev-server.js +26 -4
  20. package/build/commands/util/run-compilers.js +61 -23
  21. package/build/commands/util/run-server-watch-compiler.js +4 -2
  22. package/build/configs/app-configs/calculate-dependent-config.js +6 -1
  23. package/build/configs/app-configs/get-defaults.js +1 -0
  24. package/build/configs/app-configs/types.d.ts +11 -0
  25. package/build/configs/app-configs/validate-config.js +4 -0
  26. package/build/configs/cache/compression.d.ts +24 -0
  27. package/build/configs/cache/compression.js +120 -0
  28. package/build/configs/cache/dependencies.d.ts +4 -0
  29. package/build/configs/cache/dependencies.js +86 -0
  30. package/build/configs/cache/settings.d.ts +5 -0
  31. package/build/configs/cache/settings.js +99 -0
  32. package/build/configs/cache/storage.d.ts +17 -0
  33. package/build/configs/cache/storage.js +148 -0
  34. package/build/configs/persistent-cache.d.ts +16 -0
  35. package/build/configs/persistent-cache.js +275 -0
  36. package/build/configs/rspack.client.dev.js +3 -2
  37. package/build/configs/rspack.client.js +7 -5
  38. package/build/configs/rspack.client.prod.js +3 -2
  39. package/build/configs/rspack.server.dev.js +2 -1
  40. package/build/configs/rspack.server.js +2 -1
  41. package/build/configs/rspack.server.prod.js +2 -1
  42. package/build/configs/util/compression-plugins-for-dictionaries.js +25 -12
  43. package/build/configs/util/dcb-compression-plugin.d.ts +6 -4
  44. package/build/configs/util/dcb-compression-plugin.js +48 -82
  45. package/build/configs/util/persistent-compression-plugin.d.ts +3 -0
  46. package/build/configs/util/persistent-compression-plugin.js +41 -0
  47. package/build/index.d.ts +1 -1
  48. package/build/plugins/compression-cache.d.ts +12 -0
  49. package/build/plugins/compression-cache.js +49 -0
  50. package/build/plugins/reload-server-plugin.js +16 -0
  51. package/docs/cli.md +4 -1
  52. package/docs/commands.md +20 -0
  53. package/docs/persistent-cache.md +214 -0
  54. package/docs/settings.md +17 -0
  55. package/package.json +3 -2
  56. package/test/persistent-cache-lifecycle.cjs +124 -0
  57. package/test/persistent-cache.cjs +528 -0
  58. package/tsconfig-local.tsbuildinfo +1 -1
  59. package/tsconfig.eslint.json +1 -1
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.acquireCache = acquireCache;
7
+ exports.inspectCache = inspectCache;
8
+ exports.clearCache = clearCache;
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const MARKER = '.arui-cache.json';
13
+ const GUARD = '.operation.lock';
14
+ const LEASE = '.writer.json';
15
+ function readJson(file) {
16
+ return JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
17
+ }
18
+ function alive(pid) {
19
+ if (!Number.isSafeInteger(pid) || pid <= 0)
20
+ return true;
21
+ try {
22
+ process.kill(pid, 0);
23
+ return true;
24
+ }
25
+ catch (error) {
26
+ return error.code !== 'ESRCH';
27
+ }
28
+ }
29
+ function assertTree(directory) {
30
+ if (fs_1.default.lstatSync(directory).isSymbolicLink())
31
+ throw new Error(`Refusing cache operation: symlink ${directory}`);
32
+ fs_1.default.readdirSync(directory, { withFileTypes: true }).forEach((entry) => {
33
+ const file = path_1.default.join(directory, entry.name);
34
+ if (entry.isSymbolicLink())
35
+ throw new Error(`Refusing cache operation: symlink ${file}`);
36
+ if (entry.isDirectory())
37
+ assertTree(file);
38
+ });
39
+ }
40
+ function assertOwned(directory) {
41
+ const marker = readJson(path_1.default.join(directory, MARKER));
42
+ if (marker.tool !== 'arui-scripts/rspack' || marker.schema !== 1)
43
+ throw new Error(`Not an arui-scripts Rspack cache: ${directory}`);
44
+ }
45
+ function ownDirectory(directory) {
46
+ fs_1.default.mkdirSync(directory, { recursive: true });
47
+ const marker = path_1.default.join(directory, MARKER);
48
+ if (!fs_1.default.existsSync(marker)) {
49
+ if (fs_1.default.readdirSync(directory).length)
50
+ throw new Error(`Cache directory is not empty and has no ownership marker: ${directory}`);
51
+ try {
52
+ fs_1.default.writeFileSync(marker, JSON.stringify({ schema: 1, tool: 'arui-scripts/rspack' }), {
53
+ flag: 'wx',
54
+ });
55
+ }
56
+ catch (error) {
57
+ if (error.code !== 'EEXIST')
58
+ throw error;
59
+ }
60
+ }
61
+ assertOwned(directory);
62
+ }
63
+ function withGuard(directory, operation) {
64
+ const file = path_1.default.join(directory, GUARD);
65
+ if (fs_1.default.existsSync(file) && !alive(readJson(file).pid))
66
+ fs_1.default.unlinkSync(file);
67
+ fs_1.default.writeFileSync(file, JSON.stringify({ pid: process.pid }), { flag: 'wx' });
68
+ try {
69
+ return operation();
70
+ }
71
+ finally {
72
+ fs_1.default.unlinkSync(file);
73
+ }
74
+ }
75
+ /** The lease lasts until native compiler.close has finished flushing, not just the shutdown hook. */
76
+ function acquireCache(directory, info) {
77
+ ownDirectory(directory);
78
+ return withGuard(directory, () => {
79
+ const location = path_1.default.join(directory, info.name);
80
+ if (fs_1.default.existsSync(location))
81
+ assertTree(location);
82
+ fs_1.default.mkdirSync(location, { recursive: true });
83
+ const file = path_1.default.join(location, LEASE);
84
+ if (fs_1.default.existsSync(file)) {
85
+ if (alive(readJson(file).pid))
86
+ throw new Error(`Cache "${info.name}" has an active writer; stop it before reusing this namespace`);
87
+ fs_1.default.unlinkSync(file);
88
+ }
89
+ const token = crypto_1.default.randomBytes(16).toString('hex');
90
+ fs_1.default.writeFileSync(file, JSON.stringify({ pid: process.pid, token }), { flag: 'wx' });
91
+ try {
92
+ fs_1.default.writeFileSync(path_1.default.join(location, '.namespace.json'), JSON.stringify(info));
93
+ }
94
+ catch (error) {
95
+ fs_1.default.unlinkSync(file);
96
+ throw error;
97
+ }
98
+ return () => {
99
+ if (fs_1.default.existsSync(file) && readJson(file).token === token)
100
+ fs_1.default.unlinkSync(file);
101
+ };
102
+ });
103
+ }
104
+ function inspectCache(directory) {
105
+ if (!fs_1.default.existsSync(directory))
106
+ return { exists: false, bytes: 0, namespaces: [] };
107
+ assertOwned(directory);
108
+ assertTree(directory);
109
+ let bytes = 0;
110
+ const namespaces = [];
111
+ const visit = (current) => {
112
+ fs_1.default.readdirSync(current, { withFileTypes: true }).forEach((entry) => {
113
+ const file = path_1.default.join(current, entry.name);
114
+ if (entry.isDirectory())
115
+ visit(file);
116
+ else {
117
+ bytes += fs_1.default.statSync(file).size;
118
+ if (entry.name === '.namespace.json')
119
+ namespaces.push(readJson(file));
120
+ }
121
+ });
122
+ };
123
+ visit(directory);
124
+ return { exists: true, bytes, namespaces };
125
+ }
126
+ function clearCache(directory) {
127
+ if (!fs_1.default.existsSync(directory))
128
+ return;
129
+ assertOwned(directory);
130
+ assertTree(directory);
131
+ withGuard(directory, () => {
132
+ const entries = fs_1.default.readdirSync(directory).filter((name) => {
133
+ const namespace = path_1.default.join(directory, name);
134
+ const metadata = path_1.default.join(namespace, '.namespace.json');
135
+ if (!fs_1.default.statSync(namespace).isDirectory() || !fs_1.default.existsSync(metadata))
136
+ return false;
137
+ if (readJson(metadata).name !== name)
138
+ throw new Error(`Invalid cache namespace marker: ${namespace}`);
139
+ return true;
140
+ });
141
+ entries.forEach((name) => {
142
+ const lease = path_1.default.join(directory, name, LEASE);
143
+ if (fs_1.default.existsSync(lease) && alive(readJson(lease).pid))
144
+ throw new Error('Cache has an active writer. Stop build/dev before running cache:clear.');
145
+ });
146
+ entries.forEach((name) => fs_1.default.rmSync(path_1.default.join(directory, name), { recursive: true, force: true }));
147
+ });
148
+ }
@@ -0,0 +1,16 @@
1
+ import { type CacheOptions, type Configuration } from '@rspack/core';
2
+ /** Explicit unsupported values cause a fallback; distinct settings never share an "unknown" key. */
3
+ export declare function stableSerialize(value: unknown, normalize?: (text: string) => string): string;
4
+ export declare function getRspackCache(mode: 'dev' | 'prod', target: string): CacheOptions;
5
+ /** Called after overrides so raw cache overrides retain precedence and final outputs determine identity. */
6
+ export declare function finalizePersistentCache<T extends Configuration | Configuration[]>(configuration: T): T;
7
+ export declare function acquireCompilerCaches(configuration: Configuration | Configuration[]): Array<() => void>;
8
+ export declare function describeCompilerCaches(configuration: Configuration | Configuration[]): {
9
+ name: string;
10
+ mode: string;
11
+ policy: string;
12
+ reason: string | undefined;
13
+ target: string | false | ("async-node" | "browserslist" | "web" | "webworker" | "es3" | "es5" | "es2015" | "es2016" | "es2017" | "es2018" | "es2019" | "es2020" | "es2021" | "es2022" | "es2023" | "es2024" | "es2025" | "node" | `node${number}` | `async-node${number}` | `node${number}.${number}` | `async-node${number}.${number}` | "electron-main" | `electron${number}-main` | `electron${number}.${number}-main` | "electron-renderer" | `electron${number}-renderer` | `electron${number}.${number}-renderer` | "electron-preload" | `electron${number}-preload` | `electron${number}.${number}-preload` | "nwjs" | `nwjs${number}` | `nwjs${number}.${number}` | "node-webkit" | `node-webkit${number}` | `node-webkit${number}.${number}` | `browserslist:${string}`)[] | undefined;
14
+ namespace: string | undefined;
15
+ fingerprint: string | undefined;
16
+ }[];
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.stableSerialize = stableSerialize;
18
+ exports.getRspackCache = getRspackCache;
19
+ exports.finalizePersistentCache = finalizePersistentCache;
20
+ exports.acquireCompilerCaches = acquireCompilerCaches;
21
+ exports.describeCompilerCaches = describeCompilerCaches;
22
+ /* eslint-disable no-param-reassign -- Final configuration and cache fallback are deliberately applied in place. */
23
+ const crypto_1 = __importDefault(require("crypto"));
24
+ const fs_1 = __importDefault(require("fs"));
25
+ const path_1 = __importDefault(require("path"));
26
+ const compression_cache_1 = require("../plugins/compression-cache");
27
+ const dependencies_1 = require("./cache/dependencies");
28
+ const settings_1 = require("./cache/settings");
29
+ const storage_1 = require("./cache/storage");
30
+ const app_configs_1 = require("./app-configs");
31
+ const requested = new WeakMap();
32
+ const managed = new WeakMap();
33
+ const failures = new WeakMap();
34
+ /** Explicit unsupported values cause a fallback; distinct settings never share an "unknown" key. */
35
+ function stableSerialize(value, normalize = (text) => text) {
36
+ const active = new Set();
37
+ const visit = (item) => {
38
+ if (typeof item === 'string')
39
+ return normalize(item);
40
+ if (item === undefined)
41
+ return { $undefined: true };
42
+ if (typeof item === 'function') {
43
+ const source = Function.prototype.toString.call(item);
44
+ if (source.includes('[native code]'))
45
+ throw new Error('a bound/native function cannot be fingerprinted');
46
+ return { $function: normalize(source) };
47
+ }
48
+ if (item === null || typeof item === 'boolean' || typeof item === 'number')
49
+ return item;
50
+ if (item instanceof RegExp)
51
+ return { $regexp: item.source, flags: item.flags };
52
+ if (typeof item !== 'object')
53
+ throw new Error(`unsupported fingerprint value: ${typeof item}`);
54
+ if (active.has(item))
55
+ throw new Error('a circular setting cannot be fingerprinted');
56
+ if (!Array.isArray(item) &&
57
+ Object.getPrototypeOf(item) !== Object.prototype &&
58
+ Object.getPrototypeOf(item) !== null)
59
+ throw new Error('an opaque setting cannot be fingerprinted');
60
+ active.add(item);
61
+ const result = Array.isArray(item)
62
+ ? item.map(visit)
63
+ : Object.fromEntries(Object.keys(item)
64
+ .sort()
65
+ .map((key) => [
66
+ key,
67
+ ['plugins', 'minimizer'].includes(key) &&
68
+ Array.isArray(item[key])
69
+ ? item[key]
70
+ .filter(Boolean)
71
+ .map((plugin) => {
72
+ if (typeof plugin === 'object' &&
73
+ plugin !== null &&
74
+ !Array.isArray(plugin) &&
75
+ Object.getPrototypeOf(plugin) !== Object.prototype &&
76
+ Object.getPrototypeOf(plugin) !== null)
77
+ return { $pluginType: plugin.constructor.name };
78
+ return visit(plugin);
79
+ })
80
+ : visit(item[key]),
81
+ ]));
82
+ active.delete(item);
83
+ return result;
84
+ };
85
+ return JSON.stringify(visit(value));
86
+ }
87
+ function hash(value) {
88
+ return crypto_1.default.createHash('sha256').update(value).digest('hex');
89
+ }
90
+ function getRspackCache(mode, target) {
91
+ const settings = (0, settings_1.cacheSettings)(app_configs_1.configs);
92
+ const cacheMode = mode === 'dev' ? 'dev' : 'production';
93
+ if (!settings || !(settings.modes || ['dev', 'production']).includes(cacheMode))
94
+ return mode === 'dev';
95
+ const option = { type: 'persistent' };
96
+ requested.set(option, { mode: cacheMode, target });
97
+ return option;
98
+ }
99
+ /** Called after overrides so raw cache overrides retain precedence and final outputs determine identity. */
100
+ function finalizePersistentCache(configuration) {
101
+ const configurations = Array.isArray(configuration) ? configuration : [configuration];
102
+ configurations.forEach((config) => {
103
+ const request = config.cache && typeof config.cache === 'object'
104
+ ? requested.get(config.cache)
105
+ : undefined;
106
+ if (!request)
107
+ return;
108
+ const fallback = request.mode === 'dev';
109
+ try {
110
+ const settings = (0, settings_1.cacheSettings)(app_configs_1.configs) || {};
111
+ const directory = (0, settings_1.cacheDirectory)(app_configs_1.configs);
112
+ const normalize = settings.portable
113
+ ? (text) => text
114
+ .split(app_configs_1.configs.cwd)
115
+ .join('<project>')
116
+ .split(path_1.default.resolve(__dirname, '../..'))
117
+ .join('<arui>')
118
+ : (text) => text;
119
+ const identity = stableSerialize({
120
+ project: app_configs_1.configs.name,
121
+ target: request.target,
122
+ name: config.name,
123
+ mode: request.mode,
124
+ entry: config.entry,
125
+ output: config.output,
126
+ targetPlatform: config.target,
127
+ profile: {
128
+ module: config.module,
129
+ resolve: config.resolve,
130
+ optimization: config.optimization,
131
+ devtool: config.devtool,
132
+ externals: config.externals,
133
+ },
134
+ }, normalize);
135
+ const name = `${`${request.target}-${config.name || 'main'}-${request.mode}`
136
+ .replace(/[^a-zA-Z0-9_-]/g, '_')
137
+ .slice(0, 80)}-${hash(identity).slice(0, 20)}`;
138
+ const dependencies = (0, dependencies_1.cacheDependencies)(app_configs_1.configs);
139
+ const { plugins, cache, devServer } = config, semanticConfig = __rest(config, ["plugins", "cache", "devServer"]);
140
+ const { persistentCache } = app_configs_1.appConfigs, semanticSettings = __rest(app_configs_1.appConfigs, ["persistentCache"]);
141
+ const env = Object.fromEntries([
142
+ ...new Set([
143
+ 'NODE_ENV',
144
+ 'BABEL_ENV',
145
+ 'BROWSERSLIST',
146
+ 'BROWSERSLIST_ENV',
147
+ 'BROWSERSLIST_CONFIG',
148
+ 'USE_ISTANBUL',
149
+ ...(settings.env || []),
150
+ ]),
151
+ ]
152
+ .sort()
153
+ .map((key) => [key, process.env[key]]));
154
+ // Plugin objects are deliberately not serialized. Their definitions/imports are build dependencies;
155
+ // authors must declare dynamic env/files used by custom plugins with env/buildDependencies/version.
156
+ const version = hash(stableSerialize({
157
+ schema: 1,
158
+ toolchain: {
159
+ node: process.versions.node,
160
+ platform: process.platform,
161
+ arch: process.arch,
162
+ },
163
+ settings: semanticSettings,
164
+ config: semanticConfig,
165
+ pluginTypes: plugins === null || plugins === void 0 ? void 0 : plugins.filter(Boolean).map((plugin) => typeof plugin === 'function'
166
+ ? plugin.name
167
+ : plugin === null || plugin === void 0 ? void 0 : plugin.constructor.name),
168
+ env,
169
+ dependencies: dependencies.map(normalize),
170
+ portable: !!settings.portable,
171
+ userVersion: settings.version,
172
+ }, normalize));
173
+ const location = path_1.default.join(directory, name);
174
+ // Rspack 2.2.5 restores old readable module paths/source maps after relocation.
175
+ // Keep the semantic fingerprint portable, but partition native reuse by checkout
176
+ // until upstream relocation passes byte-for-byte artifact/source-map parity.
177
+ const checkout = hash(config.context || app_configs_1.configs.cwd);
178
+ const backendVersion = settings.portable ? `${version}-checkout-${checkout}` : version;
179
+ const metadata = path_1.default.join(location, '.namespace.json');
180
+ if (settings.portable && fs_1.default.existsSync(metadata)) {
181
+ const previous = JSON.parse(fs_1.default.readFileSync(metadata, 'utf8'));
182
+ if (previous.checkout && previous.checkout !== checkout)
183
+ console.warn('[arui-scripts cache] Checkout path changed. Rebuilding to avoid stale paths/source maps in Rspack 2.2.5; subsequent builds in this checkout can reuse the cache.');
184
+ }
185
+ config.cache = {
186
+ type: 'persistent',
187
+ name,
188
+ version: backendVersion,
189
+ buildDependencies: dependencies,
190
+ portable: settings.portable || false,
191
+ readonly: settings.readonly || false,
192
+ snapshot: { unmanagedPaths: (0, dependencies_1.linkedDependencyPaths)(app_configs_1.configs) },
193
+ storage: { type: 'filesystem', location },
194
+ };
195
+ if (settings.compression !== false) {
196
+ config.plugins = [
197
+ new compression_cache_1.CompressionCachePlugin({
198
+ location,
199
+ readonly: settings.readonly || false,
200
+ version: settings.version,
201
+ }),
202
+ ...(config.plugins || []),
203
+ ];
204
+ }
205
+ managed.set(config, {
206
+ directory,
207
+ info: {
208
+ name,
209
+ mode: request.mode,
210
+ target: request.target,
211
+ fingerprint: version,
212
+ dependencies: dependencies.length,
213
+ checkout,
214
+ },
215
+ });
216
+ }
217
+ catch (error) {
218
+ failures.set(config, 'configuration-unavailable');
219
+ console.warn(`[arui-scripts cache] Persistent cache disabled for ${request.target}: ${error.message}`);
220
+ config.cache = fallback;
221
+ }
222
+ });
223
+ return configuration;
224
+ }
225
+ function acquireCompilerCaches(configuration) {
226
+ const releases = [];
227
+ (Array.isArray(configuration) ? configuration : [configuration]).forEach((config) => {
228
+ const cache = managed.get(config);
229
+ if (!cache ||
230
+ typeof config.cache !== 'object' ||
231
+ config.cache.type !== 'persistent' ||
232
+ config.cache.readonly)
233
+ return;
234
+ try {
235
+ releases.push((0, storage_1.acquireCache)(cache.directory, cache.info));
236
+ }
237
+ catch (error) {
238
+ failures.set(config, 'storage-unavailable');
239
+ console.warn(`[arui-scripts cache] ${cache.info.name}: ${error.message}. Continuing without persistent cache.`);
240
+ config.cache = cache.info.mode === 'dev';
241
+ }
242
+ });
243
+ return releases;
244
+ }
245
+ function describeCompilerCaches(configuration) {
246
+ return (Array.isArray(configuration) ? configuration : [configuration]).map((config) => {
247
+ const cache = managed.get(config);
248
+ const mode = config.mode === 'development' ? 'dev' : 'production';
249
+ const settings = (0, settings_1.cacheSettings)(app_configs_1.configs);
250
+ const expected = (settings === null || settings === void 0 ? void 0 : settings.modes) || ['dev', 'production'];
251
+ let policy = 'legacy';
252
+ if (cache)
253
+ policy = 'arui';
254
+ else if (settings && expected.includes(mode))
255
+ policy = 'custom';
256
+ let reason = failures.get(config);
257
+ if (!reason && !settings)
258
+ reason = 'disabled-by-setting';
259
+ else if (!reason && !expected.includes(mode))
260
+ reason = 'mode-excluded';
261
+ else if (!reason && !cache)
262
+ reason = 'cache-override';
263
+ else if (!reason && cache && typeof config.cache !== 'object')
264
+ reason = 'cache-overridden-after-finalize';
265
+ return {
266
+ name: config.name || 'main',
267
+ mode,
268
+ policy,
269
+ reason,
270
+ target: (cache === null || cache === void 0 ? void 0 : cache.info.target) || config.target,
271
+ namespace: cache === null || cache === void 0 ? void 0 : cache.info.name,
272
+ fingerprint: cache === null || cache === void 0 ? void 0 : cache.info.fingerprint,
273
+ };
274
+ });
275
+ }
@@ -4,9 +4,10 @@ exports.config = void 0;
4
4
  const apply_overrides_1 = require("./util/apply-overrides");
5
5
  const find_loader_1 = require("./util/find-loader");
6
6
  const find_plugin_1 = require("./util/find-plugin");
7
+ const persistent_cache_1 = require("./persistent-cache");
7
8
  const rspack_client_1 = require("./rspack.client");
8
- exports.config = (0, apply_overrides_1.applyOverrides)(['rspack', 'rspackClient', 'rspackDev', 'rspackClientDev'], (0, rspack_client_1.createClientRspackConfig)('dev'), {
9
+ exports.config = (0, persistent_cache_1.finalizePersistentCache)((0, apply_overrides_1.applyOverrides)(['rspack', 'rspackClient', 'rspackDev', 'rspackClientDev'], (0, rspack_client_1.createClientRspackConfig)('dev'), {
9
10
  createSingleClientRspackConfig: rspack_client_1.createSingleClientRspackConfig.bind(null, 'dev'),
10
11
  findLoader: find_loader_1.findLoader,
11
12
  findPlugin: (0, find_plugin_1.createFindPluginFunction)(),
12
- });
13
+ }));
@@ -58,11 +58,13 @@ const check_node_version_1 = require("./util/check-node-version");
58
58
  const compression_plugins_for_dictionaries_1 = require("./util/compression-plugins-for-dictionaries");
59
59
  const create_watch_ignore_regex_1 = require("./util/create-watch-ignore-regex");
60
60
  const get_entry_1 = require("./util/get-entry");
61
+ const persistent_compression_plugin_1 = require("./util/persistent-compression-plugin");
61
62
  const app_configs_1 = require("./app-configs");
62
63
  const babel_client_1 = require("./babel-client");
63
64
  const babel_dependencies_1 = require("./babel-dependencies");
64
65
  const client_env_config_1 = require("./client-env-config");
65
66
  const modules_1 = require("./modules");
67
+ const persistent_cache_1 = require("./persistent-cache");
66
68
  const postcss_1 = require("./postcss");
67
69
  const process_assets_plugin_output_1 = require("./process-assets-plugin-output");
68
70
  const swc_1 = require("./swc");
@@ -182,7 +184,7 @@ const createSingleClientRspackConfig = (mode, entry, configName) => (Object.assi
182
184
  // for React Native Web.
183
185
  extensions: ['.web.js', '.mjs', '.cjs', '.js', '.json', '.web.jsx', '.jsx', '.ts', '.tsx'],
184
186
  tsConfig: app_configs_1.configs.tsconfig ? { configFile: app_configs_1.configs.tsconfig } : undefined,
185
- }, resolveLoader: {}, cache: mode === 'dev', module: {
187
+ }, resolveLoader: {}, cache: (0, persistent_cache_1.getRspackCache)(mode, 'client'), module: {
186
188
  rules: [
187
189
  {
188
190
  // "oneOf" will traverse all following loaders until one will
@@ -338,16 +340,16 @@ const createSingleClientRspackConfig = (mode, entry, configName) => (Object.assi
338
340
  // production plugins:
339
341
  mode === 'prod' && new rspack_manifest_plugin_1.RspackManifestPlugin({}),
340
342
  mode === 'prod' &&
341
- new compression_webpack_plugin_1.default({
343
+ (0, persistent_compression_plugin_1.withPersistentCompression)(new compression_webpack_plugin_1.default({
342
344
  filename: '[file].gz',
343
345
  algorithm: 'gzip',
344
346
  test: /\.js$|\.css$|\.png$|\.svg$/,
345
347
  threshold: 10240,
346
348
  minRatio: 0.8,
347
- }),
349
+ })),
348
350
  mode === 'prod' &&
349
351
  (0, check_node_version_1.checkNodeVersion)(10) &&
350
- new compression_webpack_plugin_1.default({
352
+ (0, persistent_compression_plugin_1.withPersistentCompression)(new compression_webpack_plugin_1.default({
351
353
  filename: '[file].br',
352
354
  algorithm: 'brotliCompress',
353
355
  test: /\.(js|css|html|svg|dict)$/,
@@ -358,7 +360,7 @@ const createSingleClientRspackConfig = (mode, entry, configName) => (Object.assi
358
360
  },
359
361
  threshold: 10240,
360
362
  minRatio: 0.8,
361
- }),
363
+ })),
362
364
  // Ignore prop-types packages in production mode
363
365
  // This should works fine, since proptypes usage should be eliminated in production mode
364
366
  mode === 'prod' &&
@@ -4,9 +4,10 @@ exports.rspackClientConfig = void 0;
4
4
  const apply_overrides_1 = require("./util/apply-overrides");
5
5
  const find_loader_1 = require("./util/find-loader");
6
6
  const find_plugin_1 = require("./util/find-plugin");
7
+ const persistent_cache_1 = require("./persistent-cache");
7
8
  const rspack_client_1 = require("./rspack.client");
8
- exports.rspackClientConfig = (0, apply_overrides_1.applyOverrides)(['rspack', 'rspackClient', 'rspackProd', 'rspackClientProd'], (0, rspack_client_1.createClientRspackConfig)('prod'), {
9
+ exports.rspackClientConfig = (0, persistent_cache_1.finalizePersistentCache)((0, apply_overrides_1.applyOverrides)(['rspack', 'rspackClient', 'rspackProd', 'rspackClientProd'], (0, rspack_client_1.createClientRspackConfig)('prod'), {
9
10
  createSingleClientRspackConfig: rspack_client_1.createSingleClientRspackConfig.bind(null, 'prod'),
10
11
  findLoader: find_loader_1.findLoader,
11
12
  findPlugin: (0, find_plugin_1.createFindPluginFunction)(),
12
- });
13
+ }));
@@ -4,5 +4,6 @@ exports.rspackServerConfig = void 0;
4
4
  const apply_overrides_1 = require("./util/apply-overrides");
5
5
  const find_loader_1 = require("./util/find-loader");
6
6
  const find_plugin_1 = require("./util/find-plugin");
7
+ const persistent_cache_1 = require("./persistent-cache");
7
8
  const rspack_server_1 = require("./rspack.server");
8
- exports.rspackServerConfig = (0, apply_overrides_1.applyOverrides)(['rspack', 'rspackServer', 'rspackDev', 'rspackServerDev'], (0, rspack_server_1.createServerConfig)('dev'), { findLoader: find_loader_1.findLoader, findPlugin: (0, find_plugin_1.createFindPluginFunction)() });
9
+ exports.rspackServerConfig = (0, persistent_cache_1.finalizePersistentCache)((0, apply_overrides_1.applyOverrides)(['rspack', 'rspackServer', 'rspackDev', 'rspackServerDev'], (0, rspack_server_1.createServerConfig)('dev'), { findLoader: find_loader_1.findLoader, findPlugin: (0, find_plugin_1.createFindPluginFunction)() }));
@@ -18,6 +18,7 @@ const get_entry_1 = require("./util/get-entry");
18
18
  const app_configs_1 = require("./app-configs");
19
19
  const babel_dependencies_1 = require("./babel-dependencies");
20
20
  const babel_server_1 = require("./babel-server");
21
+ const persistent_cache_1 = require("./persistent-cache");
21
22
  const postcss_1 = require("./postcss");
22
23
  const server_externals_exemptions_1 = require("./server-externals-exemptions");
23
24
  const swc_1 = require("./swc");
@@ -56,7 +57,7 @@ const createServerConfig = (mode) => ({
56
57
  // Point sourcemap entries to original disk location (format as URL on Windows)
57
58
  devtoolModuleFilenameTemplate: (info) => path_1.default.relative(app_configs_1.configs.appSrc, info.absoluteResourcePath).replace(/\\/g, '/'),
58
59
  },
59
- cache: mode === 'dev',
60
+ cache: (0, persistent_cache_1.getRspackCache)(mode, 'server'),
60
61
  externalsPresets: { node: true },
61
62
  externals: [
62
63
  (0, webpack_node_externals_1.default)(Object.assign(Object.assign({}, app_configs_1.configs.nodeExternals), { allowlist: server_externals_exemptions_1.serverExternalsExemptions })),
@@ -4,5 +4,6 @@ exports.rspackServerConfig = void 0;
4
4
  const apply_overrides_1 = require("./util/apply-overrides");
5
5
  const find_loader_1 = require("./util/find-loader");
6
6
  const find_plugin_1 = require("./util/find-plugin");
7
+ const persistent_cache_1 = require("./persistent-cache");
7
8
  const rspack_server_1 = require("./rspack.server");
8
- exports.rspackServerConfig = (0, apply_overrides_1.applyOverrides)(['rspack', 'rspackServer', 'rspackProd', 'rspackServerProd'], (0, rspack_server_1.createServerConfig)('prod'), { findLoader: find_loader_1.findLoader, findPlugin: (0, find_plugin_1.createFindPluginFunction)() });
9
+ exports.rspackServerConfig = (0, persistent_cache_1.finalizePersistentCache)((0, apply_overrides_1.applyOverrides)(['rspack', 'rspackServer', 'rspackProd', 'rspackServerProd'], (0, rspack_server_1.createServerConfig)('prod'), { findLoader: find_loader_1.findLoader, findPlugin: (0, find_plugin_1.createFindPluginFunction)() }));
@@ -13,19 +13,32 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.compressionPluginsForDictionaries = compressionPluginsForDictionaries;
16
+ const crypto_1 = __importDefault(require("crypto"));
16
17
  const fs_1 = __importDefault(require("fs"));
17
18
  const path_1 = __importDefault(require("path"));
18
19
  const app_configs_1 = require("../app-configs");
19
20
  const compress_with_dcb_1 = require("./compress-with-dcb");
20
21
  const dcb_compression_plugin_1 = require("./dcb-compression-plugin");
22
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require
23
+ const dictionaryCompressorVersion = require('brotli-dict/package.json').version;
24
+ function prepareDictionary(dictionaryContent) {
25
+ return {
26
+ key: JSON.stringify([
27
+ dictionaryCompressorVersion,
28
+ compress_with_dcb_1.compressWithDcb.toString(),
29
+ crypto_1.default.createHash('sha256').update(dictionaryContent).digest('hex'),
30
+ ]),
31
+ compress: (input) => (0, compress_with_dcb_1.compressWithDcb)(input, dictionaryContent),
32
+ };
33
+ }
21
34
  function compressionPluginsForDictionaries() {
22
35
  const predefinedPlugins = app_configs_1.configs.compressionPredefinedDictionaryPath.map((dictionaryPath) => {
23
36
  const dictionaryName = path_1.default.parse(dictionaryPath).name;
24
- const dictionaryContent = fs_1.default.readFileSync(dictionaryPath, null);
25
37
  return new dcb_compression_plugin_1.CustomCompressionPlugin({
26
38
  test: /\.js$|\.css$/,
27
39
  filename: ({ filename }) => `${filename}.${dictionaryName}.dcb`,
28
- algorithm: (input) => (0, compress_with_dcb_1.compressWithDcb)(input, dictionaryContent),
40
+ fileDependencies: [dictionaryPath],
41
+ prepare: () => prepareDictionary(fs_1.default.readFileSync(dictionaryPath)),
29
42
  threshold: 10240,
30
43
  minRatio: 0.8,
31
44
  });
@@ -48,20 +61,20 @@ function compressionPluginsForDictionaries() {
48
61
  }
49
62
  return `${parsedFilename.filename}.${matchedDictionary.hash}.dcb`;
50
63
  },
51
- algorithm: (input_1, _a) => __awaiter(this, [input_1, _a], void 0, function* (input, { filename }) {
52
- const parsedFilename = parseFilename(filename);
53
- const matchedDictionary = parsedDictionaries[`${parsedFilename.stableName}.${parsedFilename.ext}`];
54
- if (!matchedDictionary) {
55
- return input;
56
- }
64
+ fileDependencies: dictionaries.map((file) => path_1.default.join(dictionaryPath, file)),
65
+ prepare: (filename) => {
66
+ const parsed = parseFilename(filename);
67
+ const matched = parsedDictionaries[`${parsed.stableName}.${parsed.ext}`];
68
+ if (!matched)
69
+ return { key: 'missing', compress: (input) => __awaiter(this, void 0, void 0, function* () { return input; }) };
57
70
  try {
58
- const dictionaryContent = fs_1.default.readFileSync(path_1.default.join(dictionaryPath, matchedDictionary.filename), null);
59
- return yield (0, compress_with_dcb_1.compressWithDcb)(input, dictionaryContent);
71
+ const dictionaryContent = fs_1.default.readFileSync(path_1.default.join(dictionaryPath, matched.filename), null);
72
+ return prepareDictionary(dictionaryContent);
60
73
  }
61
74
  catch (e) {
62
- return input;
75
+ return { key: 'missing', compress: (input) => __awaiter(this, void 0, void 0, function* () { return input; }) };
63
76
  }
64
- }),
77
+ },
65
78
  });
66
79
  });
67
80
  return [...predefinedPlugins, ...prevVersionPlugins];
@@ -4,9 +4,12 @@ type DcbCompressionOptions = {
4
4
  test?: Rules;
5
5
  include?: Rules;
6
6
  exclude?: Rules;
7
- algorithm: (input: Buffer, options: {
8
- filename: string;
9
- }) => Promise<Buffer>;
7
+ /** Capture the dictionary bytes once so the key and compressor use the same input. */
8
+ prepare: (filename: string) => {
9
+ key: string;
10
+ compress: (input: Buffer) => Promise<Buffer>;
11
+ };
12
+ fileDependencies?: string[];
10
13
  filename: (pathdata: PathData) => string;
11
14
  threshold: number;
12
15
  minRatio: number;
@@ -14,7 +17,6 @@ type DcbCompressionOptions = {
14
17
  export declare class CustomCompressionPlugin {
15
18
  protected options: DcbCompressionOptions;
16
19
  constructor(options: DcbCompressionOptions);
17
- runCompressionAlgorithm(input: Buffer, filename: string): Promise<Buffer<ArrayBufferLike>>;
18
20
  compress(compiler: Compiler, compilation: Compilation, assets: Assets): Promise<void>;
19
21
  apply(compiler: Compiler): void;
20
22
  }