arui-scripts 26.0.0 → 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 +22 -0
  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 +2 -1
  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
@@ -11,13 +11,28 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.runClientDevServer = runClientDevServer;
13
13
  const util_1 = require("util");
14
- const core_1 = require("@rspack/core");
15
14
  const dev_server_1 = require("@rspack/dev-server");
16
15
  const dev_server_2 = require("../../configs/dev-server");
17
16
  const print_compiler_output_1 = require("../start/print-compiler-output");
17
+ const create_compiler_1 = require("./create-compiler");
18
+ const graceful_shutdown_1 = require("./graceful-shutdown");
18
19
  function runClientDevServer(configuration) {
19
20
  return __awaiter(this, void 0, void 0, function* () {
20
- const clientCompiler = (0, core_1.rspack)(configuration);
21
+ const clientCompiler = (0, create_compiler_1.createCompiler)(configuration);
22
+ let clientDevServer;
23
+ const stop = () => __awaiter(this, void 0, void 0, function* () {
24
+ let stopError;
25
+ try {
26
+ yield (clientDevServer === null || clientDevServer === void 0 ? void 0 : clientDevServer.stop());
27
+ }
28
+ catch (error) {
29
+ stopError = error instanceof Error ? error : new Error(String(error));
30
+ }
31
+ yield (0, graceful_shutdown_1.closeCompiler)(clientCompiler);
32
+ if (stopError)
33
+ throw stopError;
34
+ });
35
+ const dispose = (0, graceful_shutdown_1.registerShutdown)(stop);
21
36
  clientCompiler.hooks.invalid.tap('client', () => console.log('Compiling client...'));
22
37
  clientCompiler.hooks.done.tap('client', (stats) => (0, print_compiler_output_1.printCompilerOutput)('Client', stats));
23
38
  const DEFAULT_PORT = dev_server_2.devServerConfig.port;
@@ -30,14 +45,21 @@ function runClientDevServer(configuration) {
30
45
  });
31
46
  if (!port) {
32
47
  // We have not found a port.
33
- return;
48
+ throw new Error('No free port for the client dev server');
34
49
  }
35
50
  // dev-server слушает порт из конфига как есть, поэтому подменяем его найденным свободным
36
- const clientDevServer = new dev_server_1.RspackDevServer(Object.assign(Object.assign({}, dev_server_2.devServerConfig), { port }), clientCompiler);
51
+ clientDevServer = new dev_server_1.RspackDevServer(Object.assign(Object.assign({}, dev_server_2.devServerConfig), { port, setupExitSignals: false }), clientCompiler);
37
52
  yield clientDevServer.start();
38
53
  console.log(`Client dev server running at http://${HOST}:${port}...`);
39
54
  }
40
55
  catch (err) {
56
+ dispose();
57
+ try {
58
+ yield stop();
59
+ }
60
+ catch (closeError) {
61
+ console.error('Client cleanup failed:', closeError);
62
+ }
41
63
  if (util_1.types.isNativeError(err)) {
42
64
  console.log(err.message);
43
65
  }
@@ -7,32 +7,70 @@ exports.runCompilers = runCompilers;
7
7
  const child_process_1 = require("child_process");
8
8
  const fs_extra_1 = __importDefault(require("fs-extra"));
9
9
  const app_configs_1 = require("../../configs/app-configs");
10
+ const graceful_shutdown_1 = require("./graceful-shutdown");
10
11
  function runCompilers(pathToCompilers) {
11
- if (fs_extra_1.default.pathExistsSync(app_configs_1.configs.serverOutputPath)) {
12
+ if (fs_extra_1.default.pathExistsSync(app_configs_1.configs.serverOutputPath))
12
13
  fs_extra_1.default.removeSync(app_configs_1.configs.serverOutputPath);
14
+ const compilers = pathToCompilers.map((file) => (0, child_process_1.spawn)('node', Array.isArray(file) ? file : [file], { stdio: 'inherit', cwd: app_configs_1.configs.cwd }));
15
+ const active = new Set(compilers);
16
+ let stopping = false;
17
+ let exitCode = 0;
18
+ let timer;
19
+ const dispose = () => {
20
+ process.removeListener('SIGINT', onSignal);
21
+ process.removeListener('SIGTERM', onSignal);
22
+ if (timer)
23
+ clearTimeout(timer);
24
+ };
25
+ const finish = () => {
26
+ dispose();
27
+ if (stopping)
28
+ process.exit(exitCode);
29
+ };
30
+ const force = () => {
31
+ active.forEach((compiler) => compiler.kill('SIGKILL'));
32
+ exitCode = exitCode || 1;
33
+ finish();
34
+ };
35
+ const stop = (code) => {
36
+ if (stopping)
37
+ return;
38
+ stopping = true;
39
+ exitCode = code;
40
+ if (!active.size) {
41
+ finish();
42
+ return;
43
+ }
44
+ // Children close native compilers and flush caches before they exit.
45
+ timer = setTimeout(() => {
46
+ console.error('Compiler processes did not stop within 10 seconds.');
47
+ force();
48
+ }, graceful_shutdown_1.SHUTDOWN_TIMEOUT);
49
+ active.forEach((compiler) => compiler.kill('SIGTERM'));
50
+ };
51
+ function onSignal() {
52
+ if (stopping)
53
+ force();
54
+ else
55
+ stop(0);
13
56
  }
14
- const compilers = pathToCompilers.map((pathToCompiler) => {
15
- const compiler = (0, child_process_1.spawn)('node', Array.isArray(pathToCompiler) ? pathToCompiler : [pathToCompiler], {
16
- stdio: 'inherit',
17
- cwd: app_configs_1.configs.cwd,
57
+ process.on('SIGINT', onSignal);
58
+ process.on('SIGTERM', onSignal);
59
+ compilers.forEach((compiler) => {
60
+ compiler.on('error', (error) => {
61
+ console.error(error.message);
62
+ stop(1);
63
+ });
64
+ compiler.on('close', (code) => {
65
+ active.delete(compiler);
66
+ if (!stopping && code !== 0) {
67
+ stop(code !== null && code !== void 0 ? code : 1);
68
+ return;
69
+ }
70
+ if (stopping && code && !exitCode)
71
+ exitCode = code;
72
+ if (!active.size)
73
+ finish();
18
74
  });
19
- compiler.on('error', onProcessError);
20
- compiler.on('close', onProcessClose);
21
- return compiler;
22
75
  });
23
- function stopCompilers(exitCode) {
24
- compilers.forEach((compiler) => compiler.kill());
25
- process.exit(exitCode);
26
- }
27
- // в error приходит объект ошибки, а не код для выхода
28
- function onProcessError(error) {
29
- console.error(error.message);
30
- stopCompilers(1);
31
- }
32
- function onProcessClose(code) {
33
- if (code !== 0) {
34
- // code === null означает, что процесс убит сигналом
35
- stopCompilers(code !== null && code !== void 0 ? code : 1);
36
- }
37
- }
38
76
  }
@@ -1,12 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runServerWatchCompiler = runServerWatchCompiler;
4
- const core_1 = require("@rspack/core");
5
4
  const app_configs_1 = require("../../configs/app-configs");
6
5
  const create_watch_ignore_regex_1 = require("../../configs/util/create-watch-ignore-regex");
7
6
  const print_compiler_output_1 = require("../start/print-compiler-output");
7
+ const create_compiler_1 = require("./create-compiler");
8
+ const graceful_shutdown_1 = require("./graceful-shutdown");
8
9
  function runServerWatchCompiler(config) {
9
- const serverCompiler = (0, core_1.rspack)(config);
10
+ const serverCompiler = (0, create_compiler_1.createCompiler)(config);
11
+ (0, graceful_shutdown_1.registerShutdown)(() => (0, graceful_shutdown_1.closeCompiler)(serverCompiler));
10
12
  serverCompiler.hooks.compile.tap('server', () => console.log('Compiling server...'));
11
13
  serverCompiler.hooks.invalid.tap('server', () => console.log('Compiling server...'));
12
14
  serverCompiler.hooks.done.tap('server', (stats) => (0, print_compiler_output_1.printCompilerOutput)('Server', stats));
@@ -8,6 +8,7 @@ exports.calculateDependentContext = calculateDependentContext;
8
8
  // TODO: remove eslint-disable-next-line
9
9
  const fs_1 = __importDefault(require("fs"));
10
10
  const path_1 = __importDefault(require("path"));
11
+ const settings_1 = require("../cache/settings");
11
12
  const get_polyfills_1 = require("../util/get-polyfills");
12
13
  const resolve_1 = require("../util/resolve");
13
14
  /**
@@ -51,5 +52,9 @@ function calculateDependentContext(config, context) {
51
52
  previousVersionPath.push(p);
52
53
  }
53
54
  });
54
- return Object.assign(Object.assign({}, context), { publicPath: `${config.assetsPath}/`, serverOutputPath: path_1.default.resolve(context.cwd, config.buildPath), clientOutputPath: path_1.default.resolve(context.cwd, config.buildPath, config.assetsPath), statsOutputPath: path_1.default.resolve(context.cwd, config.buildPath, config.statsOutputFilename), watchIgnorePath: ['node_modules', config.buildPath], babelRuntimeVersion, compressionPredefinedDictionaryPath: singleFilesDictionaries, compressionPreviousVersionPath: previousVersionPath });
55
+ return Object.assign(Object.assign({}, context), { publicPath: `${config.assetsPath}/`, serverOutputPath: path_1.default.resolve(context.cwd, config.buildPath), clientOutputPath: path_1.default.resolve(context.cwd, config.buildPath, config.assetsPath), statsOutputPath: path_1.default.resolve(context.cwd, config.buildPath, config.statsOutputFilename), watchIgnorePath: [
56
+ 'node_modules',
57
+ config.buildPath,
58
+ ...(config.persistentCache ? [(0, settings_1.cacheDirectory)(Object.assign(Object.assign({}, config), context))] : []),
59
+ ], babelRuntimeVersion, compressionPredefinedDictionaryPath: singleFilesDictionaries, compressionPreviousVersionPath: previousVersionPath });
55
60
  }
@@ -59,6 +59,7 @@ function getDefaultAppConfig() {
59
59
  keepPropTypes: false,
60
60
  codeLoader: 'swc',
61
61
  experimentalReactCompiler: 'disabled',
62
+ persistentCache: false,
62
63
  installServerSourceMaps: false,
63
64
  disableDevRspackTypecheck: true,
64
65
  jestCodeTransformer: 'swc',
@@ -44,6 +44,7 @@ export type AppConfigs = {
44
44
  /** Значение 'tsc' deprecated; поддерживается только с TypeScript <7. Используйте 'swc' или 'babel'. */
45
45
  codeLoader: 'babel' | 'tsc' | 'swc';
46
46
  experimentalReactCompiler: 'disabled' | ReactCompilerOptions;
47
+ persistentCache: boolean | PersistentCacheSettings;
47
48
  installServerSourceMaps: boolean;
48
49
  disableDevRspackTypecheck: boolean;
49
50
  /** Значение 'tsc' deprecated; поддерживается только с TypeScript <7. Используйте 'swc' или 'babel'. */
@@ -92,6 +93,16 @@ export type AppConfigs = {
92
93
  } | null;
93
94
  nodeExternals?: Omit<NodeExternals.Options, 'allowlist'>;
94
95
  };
96
+ export type PersistentCacheSettings = {
97
+ compression?: boolean;
98
+ modes?: Array<'dev' | 'production'>;
99
+ directory?: string;
100
+ version?: string;
101
+ buildDependencies?: string[];
102
+ env?: string[];
103
+ portable?: boolean;
104
+ readonly?: boolean;
105
+ };
95
106
  export type ModuleConfigBase = {
96
107
  cssPrefix?: false | string;
97
108
  useSeparateBuild?: boolean;
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateConfig = validateConfig;
4
+ const settings_1 = require("../cache/settings");
4
5
  const typescript_1 = require("../util/typescript");
5
6
  const validate_build_size_budgets_1 = require("./validate-build-size-budgets");
6
7
  function validateConfig(config) {
8
+ if ((0, settings_1.cacheSettings)(config)) {
9
+ (0, settings_1.cacheDirectory)(config);
10
+ }
7
11
  (0, validate_build_size_budgets_1.validateBuildSizeBudgets)(config.buildSizeBudgets);
8
12
  const tscSettings = ['codeLoader', 'jestCodeTransformer'].filter((key) => config[key] === 'tsc');
9
13
  if (tscSettings.length > 0 &&
@@ -0,0 +1,24 @@
1
+ type Options = {
2
+ directory: string;
3
+ version: string;
4
+ readonly?: boolean;
5
+ warn?: (error: unknown) => void;
6
+ };
7
+ export declare class CompressionCache {
8
+ private options;
9
+ private pending;
10
+ private cleanup?;
11
+ private warned;
12
+ stats: {
13
+ hits: number;
14
+ misses: number;
15
+ writes: number;
16
+ };
17
+ constructor(options: Options);
18
+ resetStats(): void;
19
+ get(input: Buffer, identity: string, compress: () => Promise<Buffer>): Promise<Buffer>;
20
+ private warn;
21
+ private load;
22
+ private prune;
23
+ }
24
+ export {};
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.CompressionCache = void 0;
16
+ const crypto_1 = __importDefault(require("crypto"));
17
+ const promises_1 = __importDefault(require("fs/promises"));
18
+ const path_1 = __importDefault(require("path"));
19
+ const MAGIC = Buffer.from('ARUICMP1');
20
+ const HEADER_SIZE = MAGIC.length + 64;
21
+ const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
22
+ function digest(value) {
23
+ return crypto_1.default.createHash('sha256').update(value).digest();
24
+ }
25
+ class CompressionCache {
26
+ constructor(options) {
27
+ this.options = options;
28
+ this.pending = new Map();
29
+ this.warned = false;
30
+ this.stats = { hits: 0, misses: 0, writes: 0 };
31
+ }
32
+ resetStats() {
33
+ this.stats = { hits: 0, misses: 0, writes: 0 };
34
+ }
35
+ get(input, identity, compress) {
36
+ const key = digest(JSON.stringify([this.options.version, identity, digest(input).toString('hex')])).toString('hex');
37
+ const existing = this.pending.get(key);
38
+ if (existing)
39
+ return existing;
40
+ const result = this.load(key, compress).finally(() => this.pending.delete(key));
41
+ this.pending.set(key, result);
42
+ return result;
43
+ }
44
+ warn(error) {
45
+ var _a, _b;
46
+ if (!this.warned) {
47
+ this.warned = true;
48
+ (_b = (_a = this.options).warn) === null || _b === void 0 ? void 0 : _b.call(_a, error);
49
+ }
50
+ }
51
+ load(key, compress) {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ var _a;
54
+ if (!this.options.readonly) {
55
+ (_a = this.cleanup) !== null && _a !== void 0 ? _a : (this.cleanup = this.prune().catch((error) => this.warn(error)));
56
+ yield this.cleanup;
57
+ }
58
+ const filename = path_1.default.join(this.options.directory, key.slice(0, 2), `${key}.bin`);
59
+ try {
60
+ const record = yield promises_1.default.readFile(filename);
61
+ const output = record.subarray(HEADER_SIZE);
62
+ if (record.length < HEADER_SIZE ||
63
+ !record.subarray(0, MAGIC.length).equals(MAGIC) ||
64
+ record.subarray(MAGIC.length, MAGIC.length + 32).toString('hex') !== key ||
65
+ !record.subarray(MAGIC.length + 32, HEADER_SIZE).equals(digest(output)))
66
+ throw new Error(`Invalid compressed cache entry: ${filename}`);
67
+ this.stats.hits += 1;
68
+ return output;
69
+ }
70
+ catch (error) {
71
+ if (error.code !== 'ENOENT')
72
+ this.warn(error);
73
+ }
74
+ this.stats.misses += 1;
75
+ const output = yield compress();
76
+ if (!this.options.readonly) {
77
+ const temporary = `${filename}.${crypto_1.default.randomBytes(12).toString('hex')}.tmp`;
78
+ try {
79
+ yield promises_1.default.mkdir(path_1.default.dirname(filename), { recursive: true });
80
+ yield promises_1.default.writeFile(temporary, Buffer.concat([MAGIC, Buffer.from(key, 'hex'), digest(output), output]), { flag: 'wx' });
81
+ yield promises_1.default.rename(temporary, filename);
82
+ this.stats.writes += 1;
83
+ }
84
+ catch (error) {
85
+ this.warn(error);
86
+ }
87
+ finally {
88
+ yield promises_1.default.rm(temporary, { force: true }).catch(() => { });
89
+ }
90
+ }
91
+ return output;
92
+ });
93
+ }
94
+ prune() {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ const directories = yield promises_1.default
97
+ .readdir(this.options.directory, { withFileTypes: true })
98
+ .catch((error) => {
99
+ if (error.code === 'ENOENT')
100
+ return [];
101
+ throw error;
102
+ });
103
+ const cutoff = Date.now() - MAX_AGE_MS;
104
+ yield Promise.all(directories
105
+ .filter((entry) => entry.isDirectory() && /^[a-f0-9]{2}$/.test(entry.name))
106
+ .map((directory) => __awaiter(this, void 0, void 0, function* () {
107
+ const location = path_1.default.join(this.options.directory, directory.name);
108
+ const entries = yield promises_1.default.readdir(location, { withFileTypes: true });
109
+ yield Promise.all(entries
110
+ .filter((entry) => entry.isFile() && /^[a-f0-9]{64}\.bin$/.test(entry.name))
111
+ .map((entry) => __awaiter(this, void 0, void 0, function* () {
112
+ const file = path_1.default.join(location, entry.name);
113
+ if ((yield promises_1.default.stat(file)).mtimeMs < cutoff)
114
+ yield promises_1.default.unlink(file);
115
+ })));
116
+ })));
117
+ });
118
+ }
119
+ }
120
+ exports.CompressionCache = CompressionCache;
@@ -0,0 +1,4 @@
1
+ import { type AppContextWithConfigs } from '../app-configs/types';
2
+ /** Collect configuration inputs, including JSONC and package-based TypeScript extends. */
3
+ export declare function cacheDependencies(config: AppContextWithConfigs): string[];
4
+ export declare function linkedDependencyPaths(config: AppContextWithConfigs): string[];
@@ -0,0 +1,86 @@
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.cacheDependencies = cacheDependencies;
7
+ exports.linkedDependencyPaths = linkedDependencyPaths;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const typescript_1 = __importDefault(require("typescript"));
11
+ const read_config_file_1 = require("../app-configs/read-config-file");
12
+ const update_with_presets_1 = require("../app-configs/update-with-presets");
13
+ const settings_1 = require("./settings");
14
+ /** Collect configuration inputs, including JSONC and package-based TypeScript extends. */
15
+ function cacheDependencies(config) {
16
+ var _a, _b;
17
+ const files = new Set();
18
+ const add = (file) => {
19
+ if (fs_1.default.existsSync(file))
20
+ files.add(file);
21
+ };
22
+ for (let directory = config.cwd; directory; directory = directory === path_1.default.dirname(directory) ? '' : path_1.default.dirname(directory)) {
23
+ for (const name of [
24
+ 'package.json',
25
+ 'yarn.lock',
26
+ 'package-lock.json',
27
+ 'pnpm-lock.yaml',
28
+ 'bun.lock',
29
+ 'bun.lockb',
30
+ '.browserslistrc',
31
+ 'browserslist',
32
+ ])
33
+ add(path_1.default.join(directory, name));
34
+ }
35
+ const roots = [
36
+ (0, read_config_file_1.getConfigFilePath)(config.cwd),
37
+ config.presets ? (0, update_with_presets_1.getPresetsConfigPath)(config, config.cwd) : undefined,
38
+ ...config.overridesPath,
39
+ ];
40
+ const visited = new Set();
41
+ const visitModule = (filename) => {
42
+ var _a;
43
+ if (visited.has(filename))
44
+ return;
45
+ visited.add(filename);
46
+ add(filename);
47
+ (_a = require.cache[filename]) === null || _a === void 0 ? void 0 : _a.children.forEach((child) => visitModule(child.filename));
48
+ };
49
+ roots.forEach((filename) => {
50
+ if (filename)
51
+ visitModule(filename);
52
+ });
53
+ if (config.tsconfig) {
54
+ typescript_1.default.getParsedCommandLineOfConfigFile(config.tsconfig, {}, Object.assign(Object.assign({}, typescript_1.default.sys), { readDirectory: () => [], readFile: (file) => {
55
+ add(file);
56
+ return typescript_1.default.sys.readFile(file);
57
+ }, onUnRecoverableConfigFileDiagnostic: () => { } }));
58
+ }
59
+ if (process.env.BROWSERSLIST_CONFIG)
60
+ add(path_1.default.resolve(config.cwd, process.env.BROWSERSLIST_CONFIG));
61
+ if (config.componentsTheme) {
62
+ const theme = path_1.default.resolve(config.cwd, config.componentsTheme);
63
+ if (fs_1.default.existsSync(theme))
64
+ add(theme);
65
+ else
66
+ add(require.resolve(config.componentsTheme, { paths: [config.cwd] }));
67
+ }
68
+ config.dictionaryCompression.dictionaryPath.forEach((file) => add(path_1.default.resolve(config.cwd, file)));
69
+ (_b = (_a = (0, settings_1.cacheSettings)(config)) === null || _a === void 0 ? void 0 : _a.buildDependencies) === null || _b === void 0 ? void 0 : _b.forEach((file) => add(path_1.default.resolve(config.cwd, file)));
70
+ // Also invalidate local changes to the installed arui code, including linked development builds.
71
+ add(path_1.default.resolve(__dirname, '../../../package.json'));
72
+ add(path_1.default.resolve(__dirname, '../..'));
73
+ return [...files].sort();
74
+ }
75
+ function linkedDependencyPaths(config) {
76
+ const paths = new Set();
77
+ const names = Object.keys(Object.assign(Object.assign({}, config.appPackage.dependencies), config.appPackage.devDependencies));
78
+ names.forEach((name) => {
79
+ const candidate = path_1.default.join(config.appNodeModules, name);
80
+ if (fs_1.default.existsSync(candidate) && fs_1.default.lstatSync(candidate).isSymbolicLink()) {
81
+ paths.add(candidate);
82
+ paths.add(fs_1.default.realpathSync(candidate));
83
+ }
84
+ });
85
+ return [...paths];
86
+ }
@@ -0,0 +1,5 @@
1
+ import { type AppContextWithConfigs, type PersistentCacheSettings } from '../app-configs/types';
2
+ export declare const DEFAULT_CACHE_DIRECTORY = ".cache/arui-scripts/rspack";
3
+ export declare function containsPath(parent: string, child: string): boolean;
4
+ export declare function cacheSettings(config: AppContextWithConfigs): PersistentCacheSettings | null;
5
+ export declare function cacheDirectory(config: AppContextWithConfigs): string;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DEFAULT_CACHE_DIRECTORY = void 0;
7
+ exports.containsPath = containsPath;
8
+ exports.cacheSettings = cacheSettings;
9
+ exports.cacheDirectory = cacheDirectory;
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const os_1 = __importDefault(require("os"));
12
+ const path_1 = __importDefault(require("path"));
13
+ exports.DEFAULT_CACHE_DIRECTORY = '.cache/arui-scripts/rspack';
14
+ function containsPath(parent, child) {
15
+ const relative = path_1.default.relative(parent, child);
16
+ return (relative === '' ||
17
+ (!relative.startsWith(`..${path_1.default.sep}`) && relative !== '..' && !path_1.default.isAbsolute(relative)));
18
+ }
19
+ function cacheSettings(config) {
20
+ var _a;
21
+ const setting = config.persistentCache;
22
+ if (setting === false || setting === undefined)
23
+ return null;
24
+ if (setting === true)
25
+ return {};
26
+ if (!setting || typeof setting !== 'object' || Array.isArray(setting)) {
27
+ throw new Error('persistentCache: expected false, true or a settings object');
28
+ }
29
+ const allowed = [
30
+ 'modes',
31
+ 'directory',
32
+ 'version',
33
+ 'buildDependencies',
34
+ 'env',
35
+ 'portable',
36
+ 'readonly',
37
+ 'compression',
38
+ ];
39
+ Object.keys(setting).forEach((key) => {
40
+ if (!allowed.includes(key))
41
+ throw new Error(`persistentCache: unknown setting "${key}"`);
42
+ });
43
+ if (setting.modes !== undefined &&
44
+ (!Array.isArray(setting.modes) ||
45
+ !setting.modes.length ||
46
+ setting.modes.some((mode) => !['dev', 'production'].includes(mode)))) {
47
+ throw new Error('persistentCache.modes: expected a non-empty array of dev / production');
48
+ }
49
+ ['directory', 'version'].forEach((key) => {
50
+ if (setting[key] !== undefined &&
51
+ (typeof setting[key] !== 'string' || (key === 'directory' && !setting[key])))
52
+ throw new Error(`persistentCache.${key}: expected a string`);
53
+ });
54
+ ['portable', 'readonly', 'compression'].forEach((key) => {
55
+ if (setting[key] !== undefined && typeof setting[key] !== 'boolean')
56
+ throw new Error(`persistentCache.${key}: expected a boolean`);
57
+ });
58
+ ['buildDependencies', 'env'].forEach((key) => {
59
+ var _a;
60
+ if (setting[key] !== undefined &&
61
+ (!Array.isArray(setting[key]) ||
62
+ ((_a = setting[key]) === null || _a === void 0 ? void 0 : _a.some((value) => typeof value !== 'string' || !value))))
63
+ throw new Error(`persistentCache.${key}: expected an array of strings`);
64
+ });
65
+ (_a = setting.buildDependencies) === null || _a === void 0 ? void 0 : _a.forEach((dependency) => {
66
+ if (!fs_1.default.existsSync(path_1.default.resolve(config.cwd, dependency)))
67
+ throw new Error(`persistentCache.buildDependencies: missing path "${dependency}"`);
68
+ });
69
+ return setting;
70
+ }
71
+ function cacheDirectory(config) {
72
+ var _a;
73
+ const directory = path_1.default.resolve(config.cwd, ((_a = cacheSettings(config)) === null || _a === void 0 ? void 0 : _a.directory) || exports.DEFAULT_CACHE_DIRECTORY);
74
+ const build = path_1.default.resolve(config.cwd, config.buildPath);
75
+ const forbidden = [
76
+ path_1.default.parse(directory).root,
77
+ os_1.default.homedir(),
78
+ config.cwd,
79
+ config.appNodeModules,
80
+ path_1.default.dirname(config.cwd),
81
+ ];
82
+ if (forbidden.includes(directory) ||
83
+ containsPath(directory, config.cwd) ||
84
+ containsPath(directory, build) ||
85
+ containsPath(build, directory) ||
86
+ containsPath(directory, config.appNodeModules)) {
87
+ throw new Error(`persistentCache.directory: unsafe directory "${directory}"; use a dedicated cache directory outside buildPath`);
88
+ }
89
+ // Refuse symlinks in the path, including missing descendants of an existing symlink.
90
+ let current = directory;
91
+ while (current !== path_1.default.dirname(current)) {
92
+ if (fs_1.default.existsSync(current) &&
93
+ fs_1.default.lstatSync(current).isSymbolicLink() &&
94
+ !containsPath(current, config.cwd))
95
+ throw new Error(`persistentCache.directory: symlink is not allowed: ${current}`);
96
+ current = path_1.default.dirname(current);
97
+ }
98
+ return directory;
99
+ }
@@ -0,0 +1,17 @@
1
+ export type CacheNamespace = {
2
+ name: string;
3
+ mode: string;
4
+ target: string;
5
+ fingerprint: string;
6
+ dependencies: number;
7
+ custom?: boolean;
8
+ checkout?: string;
9
+ };
10
+ /** The lease lasts until native compiler.close has finished flushing, not just the shutdown hook. */
11
+ export declare function acquireCache(directory: string, info: CacheNamespace): () => void;
12
+ export declare function inspectCache(directory: string): {
13
+ exists: boolean;
14
+ bytes: number;
15
+ namespaces: CacheNamespace[];
16
+ };
17
+ export declare function clearCache(directory: string): void;