@xh/hoist-dev-utils 16.0.0 → 16.1.1
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/README.md +100 -26
- package/configureRsbuild.d.ts +193 -0
- package/configureRsbuild.js +65 -36
- package/configureVitest.d.ts +58 -0
- package/configureVitest.js +497 -0
- package/lib/common.js +38 -18
- package/lib/hoistCompile.js +114 -0
- package/lib/vitestInlineHoist.mjs +46 -0
- package/package.json +14 -8
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* This file belongs to Hoist, an application development toolkit
|
|
3
|
+
* developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
|
|
4
|
+
*
|
|
5
|
+
* Copyright © 2026 Extremely Heavy Industries Inc.
|
|
6
|
+
*/
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
// Imports nothing from vite or vitest - `vitest/config` does not resolve from this package under
|
|
10
|
+
// pnpm. The app wraps the returned object with its own `defineConfig()` / `mergeConfig()`.
|
|
11
|
+
const _ = require('lodash'),
|
|
12
|
+
path = require('path'),
|
|
13
|
+
fs = require('fs'),
|
|
14
|
+
{rspack, version: rsbuildVersion} = require('@rsbuild/core');
|
|
15
|
+
|
|
16
|
+
const {
|
|
17
|
+
MIN_HOIST_REACT_TEST_VERSION,
|
|
18
|
+
KNOWN_OPTIONS,
|
|
19
|
+
TEST_OPTIONS,
|
|
20
|
+
devUtilsPkg,
|
|
21
|
+
resolveAppPackage,
|
|
22
|
+
isVersionBelow,
|
|
23
|
+
discoverClientApps,
|
|
24
|
+
safeRealpath,
|
|
25
|
+
parseFlag
|
|
26
|
+
} = require('./lib/common');
|
|
27
|
+
|
|
28
|
+
const {
|
|
29
|
+
INLINE_HOIST_SINGLETONS,
|
|
30
|
+
hoistSwcTransform,
|
|
31
|
+
resolveAppIdentity,
|
|
32
|
+
resolveHoistPath,
|
|
33
|
+
xhDefines
|
|
34
|
+
} = require('./lib/hoistCompile');
|
|
35
|
+
|
|
36
|
+
// Build options a test run cannot honor - warned, then ignored. Every other build option is
|
|
37
|
+
// accepted silently, so an app can pass one `env` object to both configs.
|
|
38
|
+
const IGNORED_BUILD_OPTIONS = {extraModuleRules: 'Rspack rules cannot run under Vite'};
|
|
39
|
+
|
|
40
|
+
// Singletons beyond the build's for inline test runs: the fake server, React Testing Library (which
|
|
41
|
+
// hoist-react's setup cleans up) and MobX for apps that import it. Deduped only when the app has
|
|
42
|
+
// its own copy.
|
|
43
|
+
const INLINE_TEST_SINGLETONS = ['msw', '@testing-library/react', 'mobx'];
|
|
44
|
+
|
|
45
|
+
// Matches `@xh/hoist` and its subpaths, for the alias to a checkout.
|
|
46
|
+
const HOIST_IMPORT = /^@xh\/hoist(?=\/|$)/;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Vitest preset for Hoist unit tests. Compiles app and hoist-react code with the SWC inside Rspack
|
|
50
|
+
* and the same settings `configureRsbuild()` builds with, sets the same `XH` constants, and loads
|
|
51
|
+
* hoist-react's test setup (`@xh/hoist/test-support`). Apps consume it from a `vitest.config.mts`:
|
|
52
|
+
*
|
|
53
|
+
* import configureVitest from '@xh/hoist-dev-utils/configureVitest';
|
|
54
|
+
* import {defineConfig} from 'vitest/config';
|
|
55
|
+
* export default defineConfig(configureVitest({appCode: 'myApp'}));
|
|
56
|
+
*
|
|
57
|
+
* Import it by package name - Vite bundles a relative import of this CommonJS file, which fails.
|
|
58
|
+
* Wrap the result with `mergeConfig()` to add settings. Note that `mergeConfig()` concatenates
|
|
59
|
+
* arrays, so `include` and `setupFiles` are options here. Requires hoist-react >= 89. Run tests
|
|
60
|
+
* against a sibling hoist-react checkout with `XH_INLINE_HOIST=true vitest`.
|
|
61
|
+
*
|
|
62
|
+
* Takes the same `env` object as `configureRsbuild()`. App identity, `baseUrl`, `inlineHoist`,
|
|
63
|
+
* `extraIncludePaths`, `extraExcludePaths`, `resolveAliases` and `swcOptions` apply as in the
|
|
64
|
+
* build. Other build options are ignored - `extraModuleRules` with a warning.
|
|
65
|
+
*
|
|
66
|
+
* @param {Object} env - config passed in from the app's Vitest config.
|
|
67
|
+
* @param {string} env.appCode - as for configureRsbuild(), baked into tests as XH.appCode.
|
|
68
|
+
* @param {string} [env.appName] - as for configureRsbuild(). Defaults from appCode.
|
|
69
|
+
* @param {string} [env.appVersion] - as for configureRsbuild(). Defaults to '1.0-SNAPSHOT'.
|
|
70
|
+
* @param {string} [env.appBuild] - as for configureRsbuild(). Defaults to 'UNKNOWN'.
|
|
71
|
+
* @param {string} [env.baseUrl] - as for configureRsbuild(). Defaults to '/api/', where the fake
|
|
72
|
+
* hoist-core in `@xh/hoist/test-support` serves.
|
|
73
|
+
* @param {boolean} [env.inlineHoist=false] - true to test against a sibling hoist-react checkout at
|
|
74
|
+
* `../../hoist-react`. Also on when the `XH_INLINE_HOIST` environment variable is 'true'.
|
|
75
|
+
* @param {string[]} [env.extraIncludePaths] - custom packages to compile, as in the build.
|
|
76
|
+
* @param {string[]} [env.extraExcludePaths] - paths not to compile, as in the build.
|
|
77
|
+
* @param {Object} [env.resolveAliases] - module aliases, as in the build. A key ending in `$`
|
|
78
|
+
* matches that exact import only, and a value starting with `.` is relative to the root.
|
|
79
|
+
* @param {Object|Function} [env.swcOptions] - SWC overrides, as in the build - an object to
|
|
80
|
+
* deep-merge, or a function receiving the options. Any `env` (preset-env) key is dropped, as
|
|
81
|
+
* SWC rejects it alongside `jsc.target`.
|
|
82
|
+
* @param {string} [env.root] - project root. Defaults to the current directory.
|
|
83
|
+
* @param {string[]} [env.include] - spec globs. Defaults to `['src/**\/*.spec.{ts,tsx}']`.
|
|
84
|
+
* @param {string[]} [env.setupFiles] - app setup files, run after hoist-react's
|
|
85
|
+
* `test-support/setup.ts`.
|
|
86
|
+
* @param {?string} [env.timeZone='America/New_York'] - time zone for the run, set as `TZ`. Pass
|
|
87
|
+
* null to keep the machine's zone.
|
|
88
|
+
* @param {boolean} [env.selfHost=false] - true only for hoist-react's own config. Aliases
|
|
89
|
+
* `@xh/hoist` to the root and loads its `test-support/setup.ts`.
|
|
90
|
+
* @returns {Object} a Vite + Vitest config object.
|
|
91
|
+
*/
|
|
92
|
+
function configureVitest(env = {}) {
|
|
93
|
+
try {
|
|
94
|
+
return createConfig(env);
|
|
95
|
+
} catch (e) {
|
|
96
|
+
// The shared helpers throw strings, as the build expects. Vite's config loader cannot
|
|
97
|
+
// report one - it fails with "Invalid value used in weak set" and the message is lost.
|
|
98
|
+
throw _.isError(e) ? e : new Error(e);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function createConfig(env) {
|
|
103
|
+
const identity = resolveAppIdentity(env),
|
|
104
|
+
selfHost = parseFlag(env.selfHost, false) === true,
|
|
105
|
+
inlineHoist =
|
|
106
|
+
!selfHost &&
|
|
107
|
+
(parseFlag(env.inlineHoist, false) === true || process.env.XH_INLINE_HOIST === 'true'),
|
|
108
|
+
root = safeRealpath(path.resolve(env.root ?? process.cwd())),
|
|
109
|
+
hoistPath = selfHost ? root : resolveHoistPath(root, inlineHoist),
|
|
110
|
+
toRealPath = p => safeRealpath(path.resolve(root, p)),
|
|
111
|
+
extraIncludePaths = (env.extraIncludePaths || env.babelIncludePaths || []).map(toRealPath),
|
|
112
|
+
extraExcludePaths = (env.extraExcludePaths || env.babelExcludePaths || []).map(toRealPath),
|
|
113
|
+
include = env.include ?? ['src/**/*.spec.{ts,tsx}'],
|
|
114
|
+
setupFiles = _.castArray(env.setupFiles ?? []),
|
|
115
|
+
timeZone = env.timeZone === undefined ? 'America/New_York' : env.timeZone,
|
|
116
|
+
hoistSetup = path.join(hoistPath, 'test-support/setup.ts');
|
|
117
|
+
|
|
118
|
+
checkSwcApi();
|
|
119
|
+
if (!fs.existsSync(hoistSetup)) {
|
|
120
|
+
throw new Error(missingTestKitMessage({root, hoistPath, selfHost, inlineHoist}));
|
|
121
|
+
}
|
|
122
|
+
// Packaged mode only - a checkout or hoist-react itself may be mid-way through a vitest bump.
|
|
123
|
+
if (!selfHost && !inlineHoist) checkVitestMajor(root, hoistPath);
|
|
124
|
+
warnIgnoredOptions(env);
|
|
125
|
+
|
|
126
|
+
// Set in the main process, so test workers inherit them. Nothing reads the preset version yet -
|
|
127
|
+
// it is there for `@xh/hoist/test-support` to check against a minimum of its own.
|
|
128
|
+
if (timeZone != null) process.env.TZ = timeZone;
|
|
129
|
+
process.env.XH_VITEST_PRESET_VERSION = devUtilsPkg.version;
|
|
130
|
+
|
|
131
|
+
// Inline mode: dedupe singletons the app has its own copy of (listing one it lacks breaks the
|
|
132
|
+
// Node hook), and pass the hook its settings through a private variable. Reusing
|
|
133
|
+
// XH_INLINE_HOIST would leave inline mode on for the rest of a watch session.
|
|
134
|
+
const inlineSingletons = inlineHoist
|
|
135
|
+
? [...INLINE_HOIST_SINGLETONS, ...INLINE_TEST_SINGLETONS].filter(it =>
|
|
136
|
+
fs.existsSync(path.join(root, 'node_modules', it, 'package.json'))
|
|
137
|
+
)
|
|
138
|
+
: [];
|
|
139
|
+
if (inlineHoist) {
|
|
140
|
+
process.env.XH_VITEST_INLINE_HOIST_CFG = JSON.stringify({
|
|
141
|
+
appRoot: root,
|
|
142
|
+
hoistNodeModules: path.join(hoistPath, 'node_modules'),
|
|
143
|
+
singletons: inlineSingletons
|
|
144
|
+
});
|
|
145
|
+
} else {
|
|
146
|
+
delete process.env.XH_VITEST_INLINE_HOIST_CFG;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
root,
|
|
151
|
+
plugins: [
|
|
152
|
+
xhSwcPlugin({
|
|
153
|
+
// In selfHost, hoist-react is the root - its source already sits outside
|
|
154
|
+
// node_modules, and listing the root would also compile its dependencies' JS.
|
|
155
|
+
includePaths: selfHost ? extraIncludePaths : [hoistPath, ...extraIncludePaths],
|
|
156
|
+
// As in the build, inline mode skips the checkout's own node_modules.
|
|
157
|
+
excludePaths: inlineHoist
|
|
158
|
+
? [path.join(hoistPath, 'node_modules'), ...extraExcludePaths]
|
|
159
|
+
: extraExcludePaths,
|
|
160
|
+
swcOptions: env.swcOptions || {}
|
|
161
|
+
}),
|
|
162
|
+
xhAppChangelogPlugin(),
|
|
163
|
+
xhSkipStylesPlugin(),
|
|
164
|
+
xhMarkdownPlugin(),
|
|
165
|
+
xhGuardsPlugin()
|
|
166
|
+
],
|
|
167
|
+
|
|
168
|
+
// xh-swc owns the TS transform - Vite's Oxc cannot compile 2023-11 decorators.
|
|
169
|
+
oxc: false,
|
|
170
|
+
|
|
171
|
+
define: xhDefines({
|
|
172
|
+
...identity,
|
|
173
|
+
buildTimestamp: 0,
|
|
174
|
+
clientApps: findClientApps(root),
|
|
175
|
+
isDevelopmentMode: false
|
|
176
|
+
}),
|
|
177
|
+
|
|
178
|
+
resolve: {
|
|
179
|
+
alias: [
|
|
180
|
+
...toViteAliases(env.resolveAliases, root),
|
|
181
|
+
...(selfHost || inlineHoist ? [{find: HOIST_IMPORT, replacement: hoistPath}] : [])
|
|
182
|
+
],
|
|
183
|
+
dedupe: inlineSingletons,
|
|
184
|
+
// Vitest externalizes JS in `"type": "module"` packages, so Node would load an opt-in
|
|
185
|
+
// package natively and skip SWC. Absolute paths must be RegExps - strings match names.
|
|
186
|
+
noExternal: extraIncludePaths.map(p => new RegExp('^' + _.escapeRegExp(dirPrefix(p))))
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
// Vite serves files outside root only from allowed dirs. Setting this replaces the default,
|
|
190
|
+
// so root is listed again. This package's dir holds the inline-mode setup file.
|
|
191
|
+
server: inlineHoist ? {fs: {allow: [root, hoistPath, __dirname]}} : {},
|
|
192
|
+
|
|
193
|
+
// The settings the test kit's isolation contract needs. No `exclude` or `reporters`, so an
|
|
194
|
+
// app's values set through mergeConfig() win.
|
|
195
|
+
test: {
|
|
196
|
+
environment: 'jsdom',
|
|
197
|
+
// The Vitest default, set explicitly so Vitest stops suggesting `isolate: false`,
|
|
198
|
+
// which xh-guards rejects.
|
|
199
|
+
isolate: true,
|
|
200
|
+
include,
|
|
201
|
+
setupFiles: [
|
|
202
|
+
...(inlineHoist ? [path.join(__dirname, 'lib/vitestInlineHoist.mjs')] : []),
|
|
203
|
+
hoistSetup,
|
|
204
|
+
...setupFiles
|
|
205
|
+
],
|
|
206
|
+
// Allow for initTestAppAsync() in beforeAll, which loads the full desktop module graph.
|
|
207
|
+
hookTimeout: 30_000,
|
|
208
|
+
// Show console output only for failing tests - Hoist logs freely.
|
|
209
|
+
silent: 'passed-only',
|
|
210
|
+
restoreMocks: true,
|
|
211
|
+
unstubEnvs: true,
|
|
212
|
+
unstubGlobals: true
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
//------------------------
|
|
218
|
+
// Plugins
|
|
219
|
+
//------------------------
|
|
220
|
+
/**
|
|
221
|
+
* Compile with the SWC inside Rspack - the compiler, version and settings `configureRsbuild()`
|
|
222
|
+
* builds with. File selection mirrors Rsbuild's JS rule: any script outside node_modules, TS, TSX,
|
|
223
|
+
* JSX, MTS and CTS anywhere, and JS under `includePaths` (hoist-react and `extraIncludePaths`),
|
|
224
|
+
* minus `excludePaths`. Vite ids are real paths in posix form, so roots are compared that way.
|
|
225
|
+
*/
|
|
226
|
+
function xhSwcPlugin({includePaths, excludePaths, swcOptions}) {
|
|
227
|
+
const SCRIPT = /\.(?:[cm]?[jt]s|[jt]sx)$/,
|
|
228
|
+
ALWAYS = /\.(?:ts|tsx|jsx|mts|cts)$/,
|
|
229
|
+
TS = /\.(?:[cm]?ts|tsx)$/,
|
|
230
|
+
DECLARATION = /\.d\.[cm]?ts$/,
|
|
231
|
+
includeRoots = includePaths.map(dirPrefix),
|
|
232
|
+
excludeRoots = excludePaths.map(dirPrefix);
|
|
233
|
+
|
|
234
|
+
const shouldCompile = file => {
|
|
235
|
+
if (!SCRIPT.test(file) || DECLARATION.test(file)) return false;
|
|
236
|
+
if (excludeRoots.some(it => file.startsWith(it))) return false;
|
|
237
|
+
return (
|
|
238
|
+
!file.includes('/node_modules/') ||
|
|
239
|
+
ALWAYS.test(file) ||
|
|
240
|
+
includeRoots.some(it => file.startsWith(it))
|
|
241
|
+
);
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const optionsFor = file => {
|
|
245
|
+
const options = {
|
|
246
|
+
filename: file,
|
|
247
|
+
sourceMaps: true,
|
|
248
|
+
swcrc: false,
|
|
249
|
+
configFile: false,
|
|
250
|
+
// Rsbuild's base settings, so `swcOptions` sees the shape it gets in the build - a
|
|
251
|
+
// function that sets `env.mode` or `jsc.experimental.plugins` must not throw.
|
|
252
|
+
isModule: 'unknown',
|
|
253
|
+
env: {},
|
|
254
|
+
jsc: {
|
|
255
|
+
experimental: {keepImportAttributes: true},
|
|
256
|
+
target: 'es2022',
|
|
257
|
+
parser: TS.test(file)
|
|
258
|
+
? {syntax: 'typescript', tsx: file.endsWith('x'), decorators: true}
|
|
259
|
+
: // `accessor` fields in JS need the explicit parser flag.
|
|
260
|
+
{
|
|
261
|
+
syntax: 'ecmascript',
|
|
262
|
+
jsx: file.endsWith('x'),
|
|
263
|
+
decorators: true,
|
|
264
|
+
autoAccessors: true
|
|
265
|
+
},
|
|
266
|
+
transform: hoistSwcTransform()
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
const ret = _.isFunction(swcOptions)
|
|
270
|
+
? (swcOptions(options) ?? options)
|
|
271
|
+
: _.merge(options, swcOptions);
|
|
272
|
+
// SWC rejects `env` alongside `jsc.target`. The build's preset-env serves browsers only.
|
|
273
|
+
delete ret.env;
|
|
274
|
+
return ret;
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
return {
|
|
278
|
+
name: 'xh-swc',
|
|
279
|
+
enforce: 'pre',
|
|
280
|
+
async transform(code, id) {
|
|
281
|
+
if (id.startsWith('\0')) return null;
|
|
282
|
+
const [file, query] = id.split('?');
|
|
283
|
+
if (/(?:^|&)(?:raw|url)(?:&|=|$)/.test(query ?? '') || !shouldCompile(file)) {
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
const out = await rspack.experiments.swc.transform(code, optionsFor(file));
|
|
287
|
+
return {code: out.code, map: out.map ? JSON.parse(out.map) : null};
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Stand in for the changelog JSON that configureRsbuild() generates. */
|
|
293
|
+
function xhAppChangelogPlugin() {
|
|
294
|
+
const ID = '\0xh-app-changelog';
|
|
295
|
+
return {
|
|
296
|
+
name: 'xh-app-changelog',
|
|
297
|
+
resolveId: source => (source === '@xh/app-changelog.json' ? ID : null),
|
|
298
|
+
load: id => (id === ID ? 'export default {};' : null)
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Skip stylesheets - tests do not render styles. A style import resolves to an empty virtual
|
|
304
|
+
* module, so Vite's CSS plugin never sees a `.scss` id and apps need no Sass compiler. `?inline`,
|
|
305
|
+
* `?raw` and `?url` give an empty string, as Vitest does for CSS it skips. The build gives CSS text
|
|
306
|
+
* or a URL for those.
|
|
307
|
+
*/
|
|
308
|
+
function xhSkipStylesPlugin() {
|
|
309
|
+
const STYLE = /\.s?css(?:\?|$)/,
|
|
310
|
+
ID = '\0xh-skip-style',
|
|
311
|
+
STRING_ID = '\0xh-skip-style-string';
|
|
312
|
+
return {
|
|
313
|
+
name: 'xh-skip-styles',
|
|
314
|
+
enforce: 'pre',
|
|
315
|
+
resolveId(source) {
|
|
316
|
+
if (!STYLE.test(source)) return null;
|
|
317
|
+
const params = new URLSearchParams(source.split('?')[1]);
|
|
318
|
+
return ['inline', 'raw', 'url'].some(it => params.has(it)) ? STRING_ID : ID;
|
|
319
|
+
},
|
|
320
|
+
load(id) {
|
|
321
|
+
if (id === ID) return 'export default {};';
|
|
322
|
+
if (id === STRING_ID) return "export default '';";
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** A bare `.md` import gives the raw text, as in the build. `?url` and `?raw` fall to Vite. */
|
|
329
|
+
function xhMarkdownPlugin() {
|
|
330
|
+
return {
|
|
331
|
+
name: 'xh-markdown',
|
|
332
|
+
enforce: 'pre',
|
|
333
|
+
load(id) {
|
|
334
|
+
if (id.startsWith('\0')) return null;
|
|
335
|
+
const [file, query] = id.split('?');
|
|
336
|
+
if (!file.endsWith('.md') || query) return null;
|
|
337
|
+
return `export default ${JSON.stringify(fs.readFileSync(file, 'utf8'))};`;
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Fail the run when test files are not isolated. Each file boots its own `XH` and fake hoist-core,
|
|
344
|
+
* and module state shared across files would leak between them.
|
|
345
|
+
*/
|
|
346
|
+
function xhGuardsPlugin() {
|
|
347
|
+
return {
|
|
348
|
+
name: 'xh-guards',
|
|
349
|
+
// A named function, so a stack trace does not read as the configureVitest() factory.
|
|
350
|
+
configureVitest: function checkIsolation({project}) {
|
|
351
|
+
const {isolate, pool} = project.config;
|
|
352
|
+
if (isolate !== false) return;
|
|
353
|
+
// Vitest turns isolation off for its vm pools, whatever the isolate setting says.
|
|
354
|
+
const remedy = ['vmThreads', 'vmForks'].includes(pool)
|
|
355
|
+
? `The \`${pool}\` pool runs without it - use the \`forks\` or \`threads\` pool.`
|
|
356
|
+
: 'Remove `--no-isolate` or `isolate: false`.';
|
|
357
|
+
throw new Error(
|
|
358
|
+
'Hoist unit tests need `isolate: true` (the Vitest default) - each test file ' +
|
|
359
|
+
`boots its own XH and fake hoist-core. ${remedy}`
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
//------------------------
|
|
366
|
+
// Checks
|
|
367
|
+
//------------------------
|
|
368
|
+
// The SWC API sits under Rspack's `experiments`, with no semver promise.
|
|
369
|
+
function checkSwcApi() {
|
|
370
|
+
if (_.isFunction(rspack?.experiments?.swc?.transform)) return;
|
|
371
|
+
throw new Error(
|
|
372
|
+
`configureVitest() compiles with rspack.experiments.swc.transform, which is missing from ` +
|
|
373
|
+
`@rspack/core v${rspack?.rspackVersion} (via @rsbuild/core v${rsbuildVersion}). ` +
|
|
374
|
+
`hoist-dev-utils v${devUtilsPkg.version} expects @rsbuild/core ` +
|
|
375
|
+
`${devUtilsPkg.dependencies['@rsbuild/core']} - reinstall to restore it.`
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// The kit is found by path, so explain why it is missing in terms of the version installed.
|
|
380
|
+
function missingTestKitMessage({root, hoistPath, selfHost, inlineHoist}) {
|
|
381
|
+
const MIN = MIN_HOIST_REACT_TEST_VERSION;
|
|
382
|
+
if (selfHost) {
|
|
383
|
+
return (
|
|
384
|
+
`configureVitest() found no test-support/setup.ts in ${hoistPath} - selfHost is for ` +
|
|
385
|
+
`hoist-react's own config.`
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
if (inlineHoist) {
|
|
389
|
+
return (
|
|
390
|
+
`Inline hoist-react at ${hoistPath} has no test-support/setup.ts - pull a ` +
|
|
391
|
+
`hoist-react that has the unit test kit.`
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const {version} = resolveAppPackage('@xh/hoist', root);
|
|
396
|
+
if (version === 'NOT_FOUND') {
|
|
397
|
+
return `configureVitest() found no @xh/hoist in ${root} - install @xh/hoist >= ${MIN}.`;
|
|
398
|
+
}
|
|
399
|
+
if (isVersionBelow(version, MIN)) {
|
|
400
|
+
return (
|
|
401
|
+
`configureVitest() needs hoist-react >= ${MIN} - found v${version}. Upgrade ` +
|
|
402
|
+
`@xh/hoist to run unit tests. Builds still work with this version.`
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
return version.includes('SNAPSHOT')
|
|
406
|
+
? `@xh/hoist v${version} has no test-support/setup.ts - it predates the unit test kit. ` +
|
|
407
|
+
`Update to a newer snapshot.`
|
|
408
|
+
: `@xh/hoist v${version} has no test-support/setup.ts - the installed package is ` +
|
|
409
|
+
`missing its unit test kit.`;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Compare majors with the vitest peer range hoist-react declares, when it declares one. A
|
|
413
|
+
// major-only compare needs no semver package.
|
|
414
|
+
function checkVitestMajor(root, hoistPath) {
|
|
415
|
+
const hoistPkg = readPackageJson(hoistPath),
|
|
416
|
+
range = hoistPkg?.peerDependencies?.vitest,
|
|
417
|
+
vitestVersion = resolveAppPackage('vitest', root).version,
|
|
418
|
+
found = parseInt(vitestVersion);
|
|
419
|
+
if (!range || isNaN(found)) return;
|
|
420
|
+
|
|
421
|
+
if (!range.split('||').some(it => majorSatisfies(found, it))) {
|
|
422
|
+
throw new Error(
|
|
423
|
+
`@xh/hoist v${hoistPkg.version} supports vitest ${range} - found vitest ` +
|
|
424
|
+
`v${vitestVersion}. Install a vitest major that @xh/hoist supports.`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function warnIgnoredOptions(env) {
|
|
430
|
+
_.forEach(IGNORED_BUILD_OPTIONS, (reason, key) => {
|
|
431
|
+
if (!_.isEmpty(env[key])) warn(`configureVitest() ignores "${key}" - ${reason}.`);
|
|
432
|
+
});
|
|
433
|
+
const unknown = Object.keys(env).filter(
|
|
434
|
+
key => !KNOWN_OPTIONS.includes(key) && !TEST_OPTIONS.includes(key)
|
|
435
|
+
);
|
|
436
|
+
if (unknown.length) {
|
|
437
|
+
warn(`configureVitest() ignores unknown options (check for typos): ${unknown.join(', ')}`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
//------------------------
|
|
442
|
+
// Helpers
|
|
443
|
+
//------------------------
|
|
444
|
+
// Client apps from src/apps, as in the build - or the single default 'app' when there is none.
|
|
445
|
+
function findClientApps(root) {
|
|
446
|
+
const srcPath = path.join(root, 'src');
|
|
447
|
+
return fs.existsSync(path.join(srcPath, 'apps'))
|
|
448
|
+
? discoverClientApps(srcPath).map(it => it.name)
|
|
449
|
+
: ['app'];
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Rspack-style aliases as a Vite alias array. Rspack matches a key and its subpaths, as Vite does
|
|
453
|
+
// for a string - except a key ending in `$`, which matches that exact import only. A value starting
|
|
454
|
+
// with `.` is relative to the root, as Rsbuild resolves it - Vite would take it per importer.
|
|
455
|
+
function toViteAliases(resolveAliases, root) {
|
|
456
|
+
return _.compact(
|
|
457
|
+
_.map(resolveAliases, (value, key) => {
|
|
458
|
+
if (!_.isString(value)) {
|
|
459
|
+
warn(`configureVitest() ignores alias "${key}" - Vite takes a path string only.`);
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
const replacement = value.startsWith('.') ? path.resolve(root, value) : value;
|
|
463
|
+
return key.endsWith('$')
|
|
464
|
+
? {find: new RegExp(`^${_.escapeRegExp(key.slice(0, -1))}$`), replacement}
|
|
465
|
+
: {find: key, replacement};
|
|
466
|
+
})
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// A directory path in posix form with a trailing slash, for prefix matches against Vite ids.
|
|
471
|
+
function dirPrefix(p) {
|
|
472
|
+
return p.split(path.sep).join('/').replace(/\/?$/, '/');
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// True if a major version satisfies one `||` alternative of a semver range, by majors alone. A
|
|
476
|
+
// `>=` or `>` alternative takes its major and up, any other its first major (`^5.0.3`, `~5.1`,
|
|
477
|
+
// `5.x`), and one with no number (`*`) any major. Upper bounds and hyphen ranges are not read.
|
|
478
|
+
function majorSatisfies(major, alternative) {
|
|
479
|
+
const min = alternative.match(/\d+/)?.[0];
|
|
480
|
+
if (min == null) return true;
|
|
481
|
+
return /^\s*>/.test(alternative) ? major >= Number(min) : major === Number(min);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function readPackageJson(dir) {
|
|
485
|
+
try {
|
|
486
|
+
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
487
|
+
} catch (e) {
|
|
488
|
+
return null;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function warn(msg) {
|
|
493
|
+
console.warn(`⚠️ ${msg}`);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
module.exports = configureVitest;
|
|
497
|
+
module.exports.configureVitest = configureVitest;
|
package/lib/common.js
CHANGED
|
@@ -7,10 +7,10 @@
|
|
|
7
7
|
'use strict';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* Bundler-agnostic helpers behind `configureRsbuild()`: app / library
|
|
11
|
-
* entry-point discovery, CHANGELOG parsing, Blueprint icon stubs, manifest
|
|
12
|
-
* banner. Nothing in here touches a bundler API - anything that does
|
|
13
|
-
*
|
|
10
|
+
* Bundler-agnostic helpers behind `configureRsbuild()` and `configureVitest()`: app / library
|
|
11
|
+
* version resolution, entry-point discovery, CHANGELOG parsing, Blueprint icon stubs, manifest
|
|
12
|
+
* content, and the console banner. Nothing in here touches a bundler API - anything that does
|
|
13
|
+
* belongs in a config module or a plugin under `lib/`.
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
const _ = require('lodash'),
|
|
@@ -26,6 +26,10 @@ const _ = require('lodash'),
|
|
|
26
26
|
// earlier hoist-react's legacy `@observable` / `@bindable` fields silently stop working.
|
|
27
27
|
const MIN_HOIST_REACT_VERSION = '88';
|
|
28
28
|
|
|
29
|
+
// Minimum hoist-react version for `configureVitest()`, as 'major[.minor]' - the first release that
|
|
30
|
+
// ships the unit test kit (`@xh/hoist/test-support`). Builds keep the lower floor above.
|
|
31
|
+
const MIN_HOIST_REACT_TEST_VERSION = '89';
|
|
32
|
+
|
|
29
33
|
// Browsers targeted by transpilation and CSS processing unless the app overrides `targetBrowsers`.
|
|
30
34
|
const DEFAULT_TARGET_BROWSERS = [
|
|
31
35
|
'last 2 Chrome versions',
|
|
@@ -54,13 +58,7 @@ function resolveAppPackage(name, basePath) {
|
|
|
54
58
|
* resolvable or is a local inline checkout.
|
|
55
59
|
*/
|
|
56
60
|
function checkHoistReactVersion(hoistReactPkg, inlineHoist) {
|
|
57
|
-
|
|
58
|
-
[hrMajor, hrMinor = 0] = hoistReactPkg.version.split('.').map(Number);
|
|
59
|
-
if (
|
|
60
|
-
!inlineHoist &&
|
|
61
|
-
!isNaN(hrMajor) &&
|
|
62
|
-
(hrMajor < minMajor || (hrMajor === minMajor && hrMinor < minMinor))
|
|
63
|
-
) {
|
|
61
|
+
if (!inlineHoist && isVersionBelow(hoistReactPkg.version, MIN_HOIST_REACT_VERSION)) {
|
|
64
62
|
throw (
|
|
65
63
|
`hoist-dev-utils v${devUtilsPkg.version} requires hoist-react >= ` +
|
|
66
64
|
`${MIN_HOIST_REACT_VERSION} - found v${hoistReactPkg.version}. Upgrade @xh/hoist, ` +
|
|
@@ -69,6 +67,17 @@ function checkHoistReactVersion(hoistReactPkg, inlineHoist) {
|
|
|
69
67
|
}
|
|
70
68
|
}
|
|
71
69
|
|
|
70
|
+
/**
|
|
71
|
+
* True if `version` is below a 'major[.minor]' minimum. Any suffix (`-SNAPSHOT.<ts>`) is ignored,
|
|
72
|
+
* and a version with no numeric major (e.g. 'NOT_FOUND') is never below.
|
|
73
|
+
*/
|
|
74
|
+
function isVersionBelow(version, min) {
|
|
75
|
+
const [minMajor, minMinor = 0] = min.split('.').map(Number),
|
|
76
|
+
[major, minor = 0] = version.split('.').map(it => parseInt(it));
|
|
77
|
+
if (isNaN(major)) return false;
|
|
78
|
+
return major < minMajor || (major === minMajor && minor < minMinor);
|
|
79
|
+
}
|
|
80
|
+
|
|
72
81
|
/**
|
|
73
82
|
* Check for and resolve the standard/expected favicons within the app's /public directory,
|
|
74
83
|
* returning the manifest.json `icons` entries for those found plus an apple-touch-icon flag.
|
|
@@ -154,12 +163,15 @@ function checkNoJsxFiles(roots) {
|
|
|
154
163
|
}
|
|
155
164
|
}
|
|
156
165
|
|
|
157
|
-
/**
|
|
166
|
+
/**
|
|
167
|
+
* Resolve app entry points - one for each script within src/apps/. Unit tests there (`*.spec.*`,
|
|
168
|
+
* `*.test.*`) are skipped, so a spec can sit next to the code it tests without becoming an app.
|
|
169
|
+
*/
|
|
158
170
|
function discoverClientApps(srcPath) {
|
|
159
171
|
const appDirPath = path.resolve(srcPath, 'apps');
|
|
160
172
|
return fs
|
|
161
173
|
.readdirSync(appDirPath)
|
|
162
|
-
.filter(f => f.endsWith('.js') || f.endsWith('.ts'))
|
|
174
|
+
.filter(f => (f.endsWith('.js') || f.endsWith('.ts')) && !/\.(?:spec|test)\./.test(f))
|
|
163
175
|
.map(f => ({
|
|
164
176
|
name: f.replace('.js', '').replace('.ts', ''),
|
|
165
177
|
path: path.resolve(appDirPath, f)
|
|
@@ -357,10 +369,9 @@ function safeRealpath(p) {
|
|
|
357
369
|
}
|
|
358
370
|
}
|
|
359
371
|
|
|
360
|
-
// Normalize a boolean-ish env param. Params supplied
|
|
361
|
-
// the *string* 'false', which a bare truthiness check would read as
|
|
362
|
-
//
|
|
363
|
-
// value - notably a config object - is passed through untouched.
|
|
372
|
+
// Normalize a boolean-ish env param. Params supplied as environment variables (`XH_FOO=false`, via
|
|
373
|
+
// `readCliEnv()`) arrive as the *string* 'false', which a bare truthiness check would read as
|
|
374
|
+
// enabled. Any other value - notably a config object - is passed through untouched.
|
|
364
375
|
function parseFlag(val, dflt) {
|
|
365
376
|
if (val === undefined) return dflt;
|
|
366
377
|
if (val === 'true') return true;
|
|
@@ -369,7 +380,8 @@ function parseFlag(val, dflt) {
|
|
|
369
380
|
}
|
|
370
381
|
|
|
371
382
|
/**
|
|
372
|
-
* Every `env` option `configureRsbuild()` understands. Keep in step with its JSDoc
|
|
383
|
+
* Every `env` option `configureRsbuild()` understands. Keep in step with its JSDoc and with
|
|
384
|
+
* `configureRsbuild.d.ts` - test/declarations.test.js checks the declared keys. Options it
|
|
373
385
|
* rejects outright (`rejectUnsupported()` there) are deliberately absent.
|
|
374
386
|
*/
|
|
375
387
|
const KNOWN_OPTIONS = [
|
|
@@ -417,6 +429,10 @@ const KNOWN_OPTIONS = [
|
|
|
417
429
|
'devServerOptions'
|
|
418
430
|
];
|
|
419
431
|
|
|
432
|
+
// Options read by configureVitest() alone. Keep in step with its JSDoc and with
|
|
433
|
+
// `configureVitest.d.ts`, as for KNOWN_OPTIONS.
|
|
434
|
+
const TEST_OPTIONS = ['root', 'include', 'setupFiles', 'timeZone', 'selfHost'];
|
|
435
|
+
|
|
420
436
|
/**
|
|
421
437
|
* Warn about `env` keys the config does not recognize. A misspelled or long-removed option is otherwise
|
|
422
438
|
* ignored without a trace - one app carried a dead option for months this way. A warning rather than
|
|
@@ -442,9 +458,13 @@ function logMsg(msg) {
|
|
|
442
458
|
|
|
443
459
|
module.exports = {
|
|
444
460
|
MIN_HOIST_REACT_VERSION,
|
|
461
|
+
MIN_HOIST_REACT_TEST_VERSION,
|
|
462
|
+
KNOWN_OPTIONS,
|
|
463
|
+
TEST_OPTIONS,
|
|
445
464
|
DEFAULT_TARGET_BROWSERS,
|
|
446
465
|
devUtilsPkg,
|
|
447
466
|
resolveAppPackage,
|
|
467
|
+
isVersionBelow,
|
|
448
468
|
checkHoistReactVersion,
|
|
449
469
|
resolveIcons,
|
|
450
470
|
writeChangelogJson,
|