@xh/hoist-dev-utils 16.2.0 → 16.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -74,7 +74,7 @@ Typical `package.json` scripts:
74
74
 
75
75
  ```json
76
76
  "start": "pnpm install && rsbuild dev",
77
- "startWithHoist": "(cd ../../hoist-react && pnpm install) && pnpm install && rsbuild dev --env-mode inlineHoist",
77
+ "startWithHoist": "(cd ${XH_HOIST_REACT_PATH:-../../hoist-react} && pnpm install) && pnpm install && rsbuild dev --env-mode inlineHoist",
78
78
  "build": "rsbuild build --env-mode prod",
79
79
  "buildAndAnalyze": "cross-env RSDOCTOR=true rsbuild build --env-mode prod"
80
80
  ```
@@ -92,6 +92,90 @@ and build with `RSDOCTOR=true`, and Rsbuild registers and launches
92
92
  See the [Hoist React docs](https://github.com/xh/hoist-react/blob/develop/docs/build-and-deploy-app.md)
93
93
  for step-by-step details on the build process.
94
94
 
95
+ ### Inline Hoist
96
+
97
+ Inline mode builds the app against a local hoist-react checkout in place of the installed package,
98
+ so a library change shows up in the app as you make it. By default the checkout is a sibling of the
99
+ app's repo, at `../../hoist-react` from `client-app`.
100
+
101
+ Set `XH_HOIST_REACT_PATH` to an absolute path to use another checkout. This is how a git worktree of
102
+ an app runs against a worktree of hoist-react on a paired branch:
103
+
104
+ ```bash
105
+ XH_HOIST_REACT_PATH=~/dev/hoist-react-worktrees/my-feature pnpm startWithHoist
106
+ ```
107
+
108
+ Set it in the shell, not in a dotenv file. The `startWithHoist` and `testWithHoist` scripts read it
109
+ to install the checkout's dependencies, and Rsbuild's dotenv files do not reach them. A tool such as
110
+ direnv or mise can set it per worktree.
111
+
112
+ Inline mode fails fast when the path holds no hoist-react checkout. The Rsbuild build banner shows
113
+ the path and branch it builds from.
114
+
115
+ ### Inline packages
116
+
117
+ Inline packages extend inline mode to Hoist companion packages that ship as source, such as
118
+ `@xh/hoist-chat-kit`, `@xh/package-template` or a client library built on hoist-react. The build
119
+ runs a local checkout of the package in place of the installed copy, so a change to the package
120
+ shows up in the app as you make it.
121
+
122
+ Set `XH_INLINE_PACKAGES` to a comma-separated list of package names. Add `=/abs/path` to a name to
123
+ use a checkout at that path, which cannot contain a comma. Without a path, the checkout is a sibling
124
+ of the app's repo, named for the package without its scope:
125
+
126
+ ```bash
127
+ # ../../hoist-chat-kit from client-app
128
+ XH_INLINE_PACKAGES=@xh/hoist-chat-kit pnpm start
129
+
130
+ # A worktree, together with inline Hoist
131
+ XH_INLINE_PACKAGES=@xh/hoist-chat-kit=$HOME/dev/hoist-chat-kit-worktrees/my-feature pnpm startWithHoist
132
+ ```
133
+
134
+ `readCliEnv()` maps the variable onto the `inlinePackages` option, and `configureVitest()` reads it
135
+ too. An app config needs no change. Production builds ignore it, with a warning.
136
+
137
+ A checkout installs its own dependencies, which hold a second copy of Hoist and React for its tests
138
+ and type checks. Two copies of either break the app, so the build shares one copy of these with the
139
+ app:
140
+
141
+ - every `peerDependency` of an inline package
142
+ - `@xh/hoist`, from the inline hoist-react checkout under inline Hoist
143
+ - React, react-dom and ag-Grid, if the app has them
144
+
145
+ A shared package resolves to an inline checkout if it is one, else to the app's copy. A peer that
146
+ the app does not install resolves to Hoist's own copy. All other dependencies of the package resolve
147
+ from its checkout, as its lockfile lays them out. A companion package must declare Hoist, React and
148
+ any other library it shares with the app as `peerDependencies`.
149
+
150
+ The build fails fast if a checkout is missing, holds another package, has no `node_modules`, or
151
+ lacks a required peer. It warns if a peer range does not match the version the app runs, or if a
152
+ shared library is under `dependencies`. The build banner shows the path and branch of each checkout
153
+ and the packages it shares.
154
+
155
+ Bundler aliases do not reach `tsc` or the IDE, which still read the installed package's types. To
156
+ type-check against the checkout, add a `paths` entry for the package to the app's `tsconfig.json`,
157
+ as for inline Hoist. Do not commit it.
158
+
159
+ ```json
160
+ "paths": {
161
+ "@xh/hoist-chat-kit/*": ["../../hoist-chat-kit/*"]
162
+ }
163
+ ```
164
+
165
+ The build aliases each shared package to its directory, which bypasses the `exports` map in that
166
+ package's `package.json`. The directory then resolves through its `main`, `module` or `browser`
167
+ field. React, react-dom, ag-Grid and Hoist resolve correctly this way. A peer that has no such
168
+ field, or maps subpaths only through `exports`, fails to resolve, and the build reports the error.
169
+ Inline Hoist has the same limit.
170
+
171
+ An app alias for a shared package, such as an older hand-written alias to a checkout, gives way to
172
+ the shared copy, under inline Hoist too. The build and `configureVitest()` log a warning that names
173
+ it.
174
+
175
+ Rsbuild compiles TypeScript from any directory, `node_modules` included. An installed companion
176
+ package that ships only TypeScript therefore needs no `extraIncludePaths` entry. Add one only for a
177
+ package that also ships plain `.js` source.
178
+
95
179
  ### Migrating from v15 (webpack)
96
180
 
97
181
  Dev-utils 16 is Rsbuild only - `configureWebpack()` is gone. To move an app:
@@ -145,7 +229,7 @@ pnpm warns about any version outside those ranges. Then add scripts:
145
229
  "scripts": {
146
230
  "test": "vitest run",
147
231
  "test:watch": "vitest",
148
- "testWithHoist": "(cd ../../hoist-react && pnpm install) && pnpm install && XH_INLINE_HOIST=true vitest"
232
+ "testWithHoist": "(cd ${XH_HOIST_REACT_PATH:-../../hoist-react} && pnpm install) && pnpm install && XH_INLINE_HOIST=true vitest"
149
233
  }
150
234
  ```
151
235
 
@@ -177,7 +261,7 @@ warns about keys it does not know.
177
261
  | Option | In tests |
178
262
  |---|---|
179
263
  | `appCode` (required), `appName`, `appVersion`, `appBuild`, `baseUrl` | Set in `XH`, with the build defaults |
180
- | `inlineHoist`, `extraIncludePaths`, `extraExcludePaths`, `resolveAliases`, `swcOptions` | As in the build. An alias value that starts with `.` is relative to the root. `swcOptions` drops any `env` key, which SWC rejects with `jsc.target`. |
264
+ | `inlineHoist`, `inlinePackages`, `extraIncludePaths`, `extraExcludePaths`, `resolveAliases`, `swcOptions` | As in the build. An alias value that starts with `.` is relative to the root. `swcOptions` drops any `env` key, which SWC rejects with `jsc.target`. |
181
265
  | `extraModuleRules` | Ignored, with a warning. Rspack rules cannot run under Vite. |
182
266
  | Other build options | Ignored |
183
267
  | `root` | Project root. Default: the current directory. |
@@ -196,13 +280,18 @@ A run with `--no-isolate`, or in the `vmThreads` or `vmForks` pool, fails, becau
196
280
  boots its own `XH`. If the installed `@xh/hoist` declares a `vitest` peer dependency, the preset also
197
281
  fails on a Vitest major outside that range.
198
282
 
199
- `XH_INLINE_HOIST=true` (or `inlineHoist: true`) runs the app's tests against a hoist-react
200
- checkout at `../../hoist-react`, as `startWithHoist` does for the dev server. The preset aliases
283
+ `XH_INLINE_HOIST=true` (or `inlineHoist: true`) runs the app's tests against a local hoist-react
284
+ checkout, as `startWithHoist` does for the dev server. See [Inline Hoist](#inline-hoist) for how the
285
+ checkout is found. The preset aliases
201
286
  `@xh/hoist` to the checkout. It dedupes React, ag-Grid, msw, React Testing Library and MobX to the
202
287
  app's own copies, if the app has them. A Node resolve hook does the same for the checkout's
203
288
  dependencies, which Vitest loads outside Vite. Inline mode works under pnpm. It is untested under
204
289
  yarn and npm.
205
290
 
291
+ `XH_INLINE_PACKAGES` (or `inlinePackages`) runs the tests against local checkouts of companion
292
+ packages, with the shared copies described in [Inline packages](#inline-packages). The preset does
293
+ not collect a checkout's own specs, because `include` globs match under the project root only.
294
+
206
295
  The name matches Vitest's own `configureVitest` plugin hook. The two are unrelated: this one is a
207
296
  config factory, like `configureRsbuild()`.
208
297
 
@@ -59,10 +59,19 @@ declare namespace configureRsbuild {
59
59
  */
60
60
  baseUrl?: string;
61
61
  /**
62
- * True to use a sibling hoist-react checkout at `../../hoist-react` in place of the
63
- * installed package. Dev-mode only for the build.
62
+ * True to use a local hoist-react checkout in place of the installed package - a sibling
63
+ * at `../../hoist-react`, or the absolute path in the `XH_HOIST_REACT_PATH` environment
64
+ * variable. Dev-mode only for the build.
64
65
  */
65
66
  inlineHoist?: boolean;
67
+ /**
68
+ * Companion packages to run from a local checkout, as inlineHoist does for hoist-react -
69
+ * each `name` (a sibling checkout at `../../<name without scope>`) or `name=/abs/path`. A
70
+ * comma-separated string is also accepted. Set by the `XH_INLINE_PACKAGES` environment
71
+ * variable. Peers of an inline package, `@xh/hoist` and React resolve to one copy shared
72
+ * with the app. Dev-mode only for the build.
73
+ */
74
+ inlinePackages?: string | string[];
66
75
  /** Additional paths to transpile with the settings used for app and hoist-react code. */
67
76
  extraIncludePaths?: string[];
68
77
  /** Paths to exclude from transpiling, e.g. a local package's nested node_modules. */
@@ -22,6 +22,7 @@ const {
22
22
  devUtilsPkg,
23
23
  resolveAppPackage,
24
24
  checkHoistReactVersion,
25
+ checkRspackVersion,
25
26
  resolveIcons,
26
27
  writeChangelogJson,
27
28
  checkNoJsxFiles,
@@ -31,19 +32,22 @@ const {
31
32
  blueprintIconModulePatterns,
32
33
  generateBlueprintIconStubs,
33
34
  safeRealpath,
35
+ gitBranch,
34
36
  parseFlag,
35
37
  warnUnknownOptions,
36
38
  logSep,
37
39
  logMsg
38
40
  } = require('./lib/common');
39
41
 
42
+ const {HOIST_SWC, resolveAppIdentity, resolveHoistPath, xhDefines} = require('./lib/hoistCompile');
43
+
40
44
  const {
41
- HOIST_SWC,
42
- INLINE_HOIST_SINGLETONS,
43
- resolveAppIdentity,
44
- resolveHoistPath,
45
- xhDefines
46
- } = require('./lib/hoistCompile');
45
+ INLINE_PACKAGES_VAR,
46
+ parseInlinePackages,
47
+ planInlinePackages,
48
+ replacedAppAliases,
49
+ withInlineCacheDigest
50
+ } = require('./lib/inlinePackages');
47
51
 
48
52
  // These are not deps of hoist-dev-utils but of the consuming app, so resolve them from the
49
53
  // app's own directory (basePath).
@@ -63,10 +67,12 @@ const hoistReactPkg = resolveAppPackage('@xh/hoist', basePath),
63
67
  * Sample commands to run configurations produced by this method include:
64
68
  * `rsbuild build --env-mode prod` to trigger a production build
65
69
  * `rsbuild dev --env-mode inlineHoist` to run dev server w/hoist-react in inline mode
70
+ * `XH_INLINE_PACKAGES=@xh/hoist-chat-kit rsbuild dev` to run a companion package inline
66
71
  *
67
72
  * Note that Rsbuild's CLI has no `--env key=value` flag. Build-time overrides (appVersion, appBuild)
68
73
  * flow in as environment variables - see the `{@link readCliEnv}` helper, which maps
69
- * `XH_APP_VERSION`, `XH_APP_BUILD`, `XH_PROD_BUILD`, `XH_INLINE_HOIST`, etc. onto env options.
74
+ * `XH_APP_VERSION`, `XH_APP_BUILD`, `XH_PROD_BUILD`, `XH_INLINE_HOIST`, `XH_INLINE_PACKAGES`, etc.
75
+ * onto env options.
70
76
  *
71
77
  * @param {Object} env - config passed in from the app's rsbuild config.
72
78
  * @param {string} env.appCode - short, internal code for the application - baked into client as XH.appCode. Should be
@@ -78,7 +84,18 @@ const hoistReactPkg = resolveAppPackage('@xh/hoist', basePath),
78
84
  * @param {boolean} [env.prodBuild=false] - true to indicate this is a build (as opposed to run of the dev server)
79
85
  * @param {boolean} [env.inlineHoist=false] - true to use a locally checked-out copy of hoist-react
80
86
  * when running the dev server, as opposed to using the downloaded dependency. This allows
81
- * hoist-react developers to test plugin changes. Dev-mode only.
87
+ * hoist-react developers to test plugin changes. Dev-mode only. The checkout is a sibling of
88
+ * the app's repo at `../../hoist-react`, unless the `XH_HOIST_REACT_PATH` environment variable
89
+ * names another (absolute) path, e.g. a git worktree.
90
+ * @param {(string|string[])} [env.inlinePackages] - companion packages to run from a local checkout
91
+ * in place of the installed copy, as inlineHoist does for hoist-react - e.g.
92
+ * `@xh/hoist-chat-kit`. Each entry is `name`, for a checkout that is a sibling of the app's repo
93
+ * named for the package without its scope (`../../hoist-chat-kit`), or `name=/abs/path`. A
94
+ * comma-separated string is also accepted, as set by the `XH_INLINE_PACKAGES` environment
95
+ * variable. Every peerDependency of an inline package, plus `@xh/hoist` and React, resolves to
96
+ * a single copy shared with the app - the inline checkout where there is one. Its other
97
+ * dependencies resolve from its own checkout. Dev-mode only - ignored with a warning when
98
+ * prodBuild is true.
82
99
  * @param {boolean} [env.reactProdMode=false] - true to use the production build of React
83
100
  * when running the dev server.
84
101
  * @param {Object} [env.resolveAliases] - object mapping for custom module resolution.
@@ -162,6 +179,8 @@ async function configureRsbuild(env) {
162
179
 
163
180
  const prodBuild = parseFlag(env.prodBuild, false) === true,
164
181
  inlineHoist = !prodBuild && parseFlag(env.inlineHoist, false) === true,
182
+ // Not parsed for prod builds, where a stray value must not fail the build.
183
+ inlinePackageSpecs = prodBuild ? [] : parseInlinePackages(env.inlinePackages),
165
184
  reactProdMode = prodBuild || parseFlag(env.reactProdMode, false) === true,
166
185
  resolveAliases = Object.assign({}, env.resolveAliases),
167
186
  buildCache = _.isPlainObject(env.buildCache)
@@ -206,6 +225,23 @@ async function configureRsbuild(env) {
206
225
  }
207
226
  }
208
227
  checkHoistReactVersion(hoistReactPkg, inlineHoist);
228
+ checkRspackVersion(rspack.rspackVersion);
229
+
230
+ // Resolve Hoist as either a local checkout (inline) or a downloaded package. Inline mode throws
231
+ // here, before any output, when the checkout is missing. Symlinks are resolved (a no-op for
232
+ // flat layouts) so the path matches the real module paths Rspack produces via its default
233
+ // resolve.symlinks behavior - required for the transpile include below to match under
234
+ // symlinking package managers (e.g. pnpm).
235
+ const hoistPath = resolveHoistPath(basePath, inlineHoist);
236
+
237
+ // Plan inline packages - throws here, as above, when a checkout or a required peer is missing.
238
+ const inlinePlan = planInlinePackages({
239
+ appRoot: basePath,
240
+ specs: inlinePackageSpecs,
241
+ hoistPath,
242
+ inlineHoist
243
+ }),
244
+ inlinePackages = inlinePlan.packages;
209
245
 
210
246
  process.env.NODE_ENV = prodBuild ? 'production' : 'development';
211
247
  process.env.REACT_NODE_ENV = reactProdMode ? 'production' : 'development';
@@ -218,12 +254,25 @@ async function configureRsbuild(env) {
218
254
  if (prodBuild) logMsg('🚀 Production build enabled');
219
255
  if (!prodBuild) logMsg('💻 Development mode enabled');
220
256
  if (inlineHoist) logMsg('🏗️ Inline Hoist enabled');
257
+ if (inlinePackages.length) logMsg('📦 Inline packages enabled');
258
+ if (prodBuild && !_.isEmpty(env.inlinePackages)) {
259
+ logMsg(`⚠️ Inline packages ignored for production builds (${INLINE_PACKAGES_VAR}).`);
260
+ }
221
261
  if (reactProdMode) logMsg('⚛️ React Production mode enabled');
222
262
  if (buildCache) logMsg('💾 Persistent build cache enabled');
223
263
  if (prodBuild && precompressAssets) logMsg('🗜️ Asset pre-compression enabled');
224
264
  logSep();
225
265
  logMsg('📚 Key libraries:');
226
- logMsg(` > @xh/hoist ${inlineHoist ? 'INLINE' : 'v' + hoistReactPkg.version}`);
266
+ if (inlineHoist) {
267
+ const branch = gitBranch(hoistPath);
268
+ logMsg(` > @xh/hoist INLINE from ${hoistPath}${branch ? ` @ ${branch}` : ''}`);
269
+ } else {
270
+ logMsg(` > @xh/hoist v${hoistReactPkg.version}`);
271
+ }
272
+ inlinePackages.forEach(({name, path: dir}) => {
273
+ const branch = gitBranch(dir);
274
+ logMsg(` > ${name} INLINE from ${dir}${branch ? ` @ ${branch}` : ''}`);
275
+ });
227
276
  logMsg(` > @xh/hoist-dev-utils v${devUtilsPkg.version}`);
228
277
  logMsg(` > react v${reactPkg.version}`);
229
278
  logMsg(` > @rsbuild/core v${rsbuildVersion}`);
@@ -232,6 +281,15 @@ async function configureRsbuild(env) {
232
281
  logSep();
233
282
  logMsg('🎯 Targets:');
234
283
  targetBrowsers.forEach(it => logMsg(` > ${it}`));
284
+ if (inlinePlan.shared.length) {
285
+ logSep();
286
+ logMsg('🔗 Shared inline, one copy each:');
287
+ inlinePlan.shared.forEach(({name, dir}) => logMsg(` > ${name} from ${dir}`));
288
+ inlinePlan.warnings.forEach(it => logMsg(`⚠️ ${it}`));
289
+ replacedAppAliases(env.resolveAliases, inlinePlan.shared).forEach(key =>
290
+ logMsg(`⚠️ App alias "${key}" replaced by the shared copy above.`)
291
+ );
292
+ }
235
293
 
236
294
  const srcPath = path.resolve(basePath, 'src'),
237
295
  outPath = path.resolve(basePath, 'build'),
@@ -240,12 +298,6 @@ async function configureRsbuild(env) {
240
298
  // linked - avoids assuming the package is physically within the app's node_modules.
241
299
  hoistDevUtilsPath = __dirname;
242
300
 
243
- // Resolve Hoist as either a sibling (inline, checked-out) project or a downloaded package.
244
- // Resolve symlinks (a no-op for flat layouts) so the path matches the real module paths
245
- // Rspack produces via its default resolve.symlinks behavior - required for the transpile
246
- // include below to match under symlinking package managers (e.g. pnpm).
247
- const hoistPath = resolveHoistPath(basePath, inlineHoist);
248
-
249
301
  // Check for and resolve standard/expected favicons.
250
302
  const {manifestIcons, appleTouchIconExists} = resolveIcons(
251
303
  publicAssetsPath,
@@ -259,20 +311,25 @@ async function configureRsbuild(env) {
259
311
  ? null
260
312
  : generateBlueprintIconStubs(basePath, hoistPath);
261
313
 
262
- // Tell the bundler where to look for modules when resolving imports - this is the key to
263
- // getting inlineHoist mode to look in within the checked-out hoist-react project at hoistPath.
264
- if (inlineHoist) {
265
- resolveAliases['@xh/hoist'] = hoistPath;
266
-
267
- // Use the app's instance of each library hoist-react must share with it - React for hooks,
268
- // ag-Grid for `useGridMenuItem`. See INLINE_HOIST_SINGLETONS.
269
- INLINE_HOIST_SINGLETONS.forEach(name => {
270
- resolveAliases[name] = path.resolve('./node_modules', name);
271
- });
272
- }
314
+ // Inline mode: alias each shared name to the one copy every importer gets - each checkout,
315
+ // hoist-react's included, plus their peers and the libraries hoist-react must share with the
316
+ // app (React for hooks, ag-Grid for `useGridMenuItem`). Aliases are global, so the dependencies
317
+ // a checkout installs share that copy too. See lib/inlinePackages.js.
318
+ replacedAppAliases(resolveAliases, inlinePlan.shared).forEach(key => {
319
+ delete resolveAliases[key];
320
+ });
321
+ inlinePlan.shared.forEach(({name, dir}) => {
322
+ resolveAliases[name] = dir;
323
+ });
273
324
 
274
- // When running inline, resolve inline Hoist's own node_modules so we can exclude them.
275
- const hoistNodeModulesPath = inlineHoist ? path.resolve(hoistPath, 'node_modules') : null;
325
+ // When running inline, resolve the checkouts' own node_modules so we can exclude them. Their
326
+ // dependencies ship built - compiling them would be slow, and could break them.
327
+ const hoistNodeModulesPath = inlineHoist ? path.resolve(hoistPath, 'node_modules') : null,
328
+ inlineSrcPaths = inlinePackages.map(it => it.path),
329
+ inlineExcludePaths = _.compact([
330
+ hoistNodeModulesPath,
331
+ ...inlinePackages.map(it => it.nodeModules)
332
+ ]);
276
333
 
277
334
  // Determine source map (devtool) mode.
278
335
  let devtool;
@@ -357,8 +414,8 @@ async function configureRsbuild(env) {
357
414
  splitChunks: false,
358
415
  reactRefreshOptions: {
359
416
  // Refresh app source, hoist-react (raw TS in node_modules) and custom packages.
360
- include: [srcPath, hoistPath, ...extraIncludePaths],
361
- exclude: hoistNodeModulesPath ? [hoistNodeModulesPath] : []
417
+ include: [srcPath, hoistPath, ...inlineSrcPaths, ...extraIncludePaths],
418
+ exclude: inlineExcludePaths
362
419
  }
363
420
  }),
364
421
 
@@ -380,9 +437,9 @@ async function configureRsbuild(env) {
380
437
  // currently transpiling anything in hoist-react on its own. (Rsbuild's default include
381
438
  // also compiles every .ts/.tsx it encounters, so this is largely belt-and-braces for
382
439
  // hoist's plain-JS `polyfills.js` and any custom packages.)
383
- include: [srcPath, hoistPath, ...extraIncludePaths],
384
- // In inline mode also *avoid* transpiling inline hoist's own node_modules libraries.
385
- exclude: inlineHoist ? [hoistNodeModulesPath, ...extraExcludePaths] : extraExcludePaths,
440
+ include: [srcPath, hoistPath, ...inlineSrcPaths, ...extraIncludePaths],
441
+ // In inline mode also *avoid* transpiling the checkouts' own node_modules libraries.
442
+ exclude: [...inlineExcludePaths, ...extraExcludePaths],
386
443
 
387
444
  // TC39 Stage 3 (2023-11) decorators, transformed by SWC alone - no Babel pass. This is
388
445
  // the emit hoist-react >= 88 is written against: `@observable accessor` / `@bindable
@@ -537,7 +594,12 @@ async function configureRsbuild(env) {
537
594
  },
538
595
 
539
596
  performance: {
540
- buildCache,
597
+ // Inline settings change module resolution, so they key the cache too.
598
+ buildCache: withInlineCacheDigest(buildCache, {
599
+ inlineHoist,
600
+ hoistPath,
601
+ packages: inlinePackages
602
+ }),
541
603
  printFileSize: prodBuild ? {detail: false} : false
542
604
  },
543
605
 
@@ -841,6 +903,7 @@ function readCliEnv(processEnv = process.env) {
841
903
  XH_APP_BUILD: 'appBuild',
842
904
  XH_PROD_BUILD: 'prodBuild',
843
905
  XH_INLINE_HOIST: 'inlineHoist',
906
+ [INLINE_PACKAGES_VAR]: 'inlinePackages',
844
907
  XH_REACT_PROD_MODE: 'reactProdMode',
845
908
  XH_BUILD_CACHE: 'buildCache',
846
909
  XH_MINIFY: 'minify',
@@ -26,13 +26,19 @@ const {
26
26
  } = require('./lib/common');
27
27
 
28
28
  const {
29
- INLINE_HOIST_SINGLETONS,
30
29
  hoistSwcTransform,
31
30
  resolveAppIdentity,
32
31
  resolveHoistPath,
33
32
  xhDefines
34
33
  } = require('./lib/hoistCompile');
35
34
 
35
+ const {
36
+ INLINE_PACKAGES_VAR,
37
+ parseInlinePackages,
38
+ planInlinePackages,
39
+ replacedAppAliases
40
+ } = require('./lib/inlinePackages');
41
+
36
42
  // Build options a test run cannot honor - warned, then ignored. Every other build option is
37
43
  // accepted silently, so an app can pass one `env` object to both configs.
38
44
  const IGNORED_BUILD_OPTIONS = {extraModuleRules: 'Rspack rules cannot run under Vite'};
@@ -57,11 +63,11 @@ const HOIST_IMPORT = /^@xh\/hoist(?=\/|$)/;
57
63
  * Import it by package name - Vite bundles a relative import of this CommonJS file, which fails.
58
64
  * Wrap the result with `mergeConfig()` to add settings. Note that `mergeConfig()` concatenates
59
65
  * 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`.
66
+ * against a local hoist-react checkout with `XH_INLINE_HOIST=true vitest`.
61
67
  *
62
68
  * 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.
69
+ * `inlinePackages`, `extraIncludePaths`, `extraExcludePaths`, `resolveAliases` and `swcOptions`
70
+ * apply as in the build. Other build options are ignored - `extraModuleRules` with a warning.
65
71
  *
66
72
  * @param {Object} env - config passed in from the app's Vitest config.
67
73
  * @param {string} env.appCode - as for configureRsbuild(), baked into tests as XH.appCode.
@@ -70,8 +76,13 @@ const HOIST_IMPORT = /^@xh\/hoist(?=\/|$)/;
70
76
  * @param {string} [env.appBuild] - as for configureRsbuild(). Defaults to 'UNKNOWN'.
71
77
  * @param {string} [env.baseUrl] - as for configureRsbuild(). Defaults to '/api/', where the fake
72
78
  * 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'.
79
+ * @param {boolean} [env.inlineHoist=false] - true to test against a local hoist-react checkout, as
80
+ * for configureRsbuild() - a sibling at `../../hoist-react`, or the path in the
81
+ * `XH_HOIST_REACT_PATH` environment variable. Also on when `XH_INLINE_HOIST` is 'true'.
82
+ * @param {(string|string[])} [env.inlinePackages] - companion packages to test from a local
83
+ * checkout, as for configureRsbuild(). Read from the `XH_INLINE_PACKAGES` environment
84
+ * variable when not passed. The checkout's own specs are not collected - `include` globs
85
+ * match under the root only.
75
86
  * @param {string[]} [env.extraIncludePaths] - custom packages to compile, as in the build.
76
87
  * @param {string[]} [env.extraExcludePaths] - paths not to compile, as in the build.
77
88
  * @param {Object} [env.resolveAliases] - module aliases, as in the build. A key ending in `$`
@@ -113,7 +124,18 @@ function createConfig(env) {
113
124
  include = env.include ?? ['src/**/*.spec.{ts,tsx}'],
114
125
  setupFiles = _.castArray(env.setupFiles ?? []),
115
126
  timeZone = env.timeZone === undefined ? 'America/New_York' : env.timeZone,
116
- hoistSetup = path.join(hoistPath, 'test-support/setup.ts');
127
+ hoistSetup = path.join(hoistPath, 'test-support/setup.ts'),
128
+ inlinePlan = planInlinePackages({
129
+ appRoot: root,
130
+ specs: selfHost
131
+ ? []
132
+ : parseInlinePackages(env.inlinePackages ?? process.env[INLINE_PACKAGES_VAR]),
133
+ hoistPath,
134
+ inlineHoist,
135
+ extraSingletons: INLINE_TEST_SINGLETONS
136
+ }),
137
+ inlinePackages = inlinePlan.packages,
138
+ anyInline = inlineHoist || inlinePackages.length > 0;
117
139
 
118
140
  checkSwcApi();
119
141
  if (!fs.existsSync(hoistSetup)) {
@@ -122,25 +144,44 @@ function createConfig(env) {
122
144
  // Packaged mode only - a checkout or hoist-react itself may be mid-way through a vitest bump.
123
145
  if (!selfHost && !inlineHoist) checkVitestMajor(root, hoistPath);
124
146
  warnIgnoredOptions(env);
147
+ inlinePlan.warnings.forEach(warn);
148
+
149
+ // As in the build, the shared copies win over an app alias for the same package.
150
+ const replacedAliases = replacedAppAliases(env.resolveAliases, inlinePlan.shared);
151
+ replacedAliases.forEach(key => warn(`App alias "${key}" replaced by an inline shared copy.`));
125
152
 
126
153
  // Set in the main process, so test workers inherit them. Nothing reads the preset version yet -
127
154
  // it is there for `@xh/hoist/test-support` to check against a minimum of its own.
128
155
  if (timeZone != null) process.env.TZ = timeZone;
129
156
  process.env.XH_VITEST_PRESET_VERSION = devUtilsPkg.version;
130
157
 
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) {
158
+ // Inline mode: dedupe the shared packages the app has its own copy of - singletons and the
159
+ // peers of inline packages. Hoist and the checkouts are aliased below. See
160
+ // lib/inlinePackages.js.
161
+ const inlineSingletons = inlinePlan.shared
162
+ .filter(it => it.source === 'app' && it.name !== '@xh/hoist')
163
+ .map(it => it.name);
164
+
165
+ // Aliases for the inline packages and for a peer taken from Hoist's own copy, which the app
166
+ // does not install - `dedupe` resolves from the root only.
167
+ const inlineAliases = inlinePlan.shared
168
+ .filter(it => it.name !== '@xh/hoist' && it.source !== 'app')
169
+ .map(it => ({find: it.name, replacement: it.dir}));
170
+
171
+ // Pass the Node hook its settings through a private variable. Reusing XH_INLINE_HOIST would
172
+ // leave inline mode on for the rest of a watch session.
173
+ if (anyInline) {
140
174
  process.env.XH_VITEST_INLINE_HOIST_CFG = JSON.stringify({
141
- appRoot: root,
142
- hoistNodeModules: path.join(hoistPath, 'node_modules'),
143
- singletons: inlineSingletons
175
+ fromDirs: [
176
+ ...(inlineHoist ? [path.join(hoistPath, 'node_modules')] : []),
177
+ ...inlinePackages.map(it => it.nodeModules)
178
+ ],
179
+ singletons: [
180
+ ...inlineSingletons.map(name => ({name, from: root})),
181
+ ...inlinePlan.shared
182
+ .filter(it => it.source === 'hoist')
183
+ .map(it => ({name: it.name, from: nodeModulesParent(it.dir)}))
184
+ ]
144
185
  });
145
186
  } else {
146
187
  delete process.env.XH_VITEST_INLINE_HOIST_CFG;
@@ -152,11 +193,15 @@ function createConfig(env) {
152
193
  xhSwcPlugin({
153
194
  // In selfHost, hoist-react is the root - its source already sits outside
154
195
  // 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,
196
+ includePaths: selfHost
197
+ ? extraIncludePaths
198
+ : [hoistPath, ...inlinePackages.map(it => it.path), ...extraIncludePaths],
199
+ // As in the build, inline mode skips the checkouts' own node_modules.
200
+ excludePaths: [
201
+ ...(inlineHoist ? [path.join(hoistPath, 'node_modules')] : []),
202
+ ...inlinePackages.map(it => it.nodeModules),
203
+ ...extraExcludePaths
204
+ ],
160
205
  swcOptions: env.swcOptions || {}
161
206
  }),
162
207
  xhAppChangelogPlugin(),
@@ -177,8 +222,10 @@ function createConfig(env) {
177
222
 
178
223
  resolve: {
179
224
  alias: [
180
- ...toViteAliases(env.resolveAliases, root),
181
- ...(selfHost || inlineHoist ? [{find: HOIST_IMPORT, replacement: hoistPath}] : [])
225
+ ...toViteAliases(_.omit(env.resolveAliases, replacedAliases), root),
226
+ ...inlineAliases,
227
+ // Inline packages import Hoist too, and must reach this copy, not their own.
228
+ ...(selfHost || anyInline ? [{find: HOIST_IMPORT, replacement: hoistPath}] : [])
182
229
  ],
183
230
  dedupe: inlineSingletons,
184
231
  // Vitest externalizes JS in `"type": "module"` packages, so Node would load an opt-in
@@ -188,7 +235,18 @@ function createConfig(env) {
188
235
 
189
236
  // Vite serves files outside root only from allowed dirs. Setting this replaces the default,
190
237
  // so root is listed again. This package's dir holds the inline-mode setup file.
191
- server: inlineHoist ? {fs: {allow: [root, hoistPath, __dirname]}} : {},
238
+ server: anyInline
239
+ ? {
240
+ fs: {
241
+ allow: [
242
+ root,
243
+ ...(inlineHoist ? [hoistPath] : []),
244
+ ...inlinePackages.map(it => it.path),
245
+ __dirname
246
+ ]
247
+ }
248
+ }
249
+ : {},
192
250
 
193
251
  // The settings the test kit's isolation contract needs. No `exclude` or `reporters`, so an
194
252
  // app's values set through mergeConfig() win.
@@ -199,7 +257,7 @@ function createConfig(env) {
199
257
  isolate: true,
200
258
  include,
201
259
  setupFiles: [
202
- ...(inlineHoist ? [path.join(__dirname, 'lib/vitestInlineHoist.mjs')] : []),
260
+ ...(anyInline ? [path.join(__dirname, 'lib/vitestInlineHoist.mjs')] : []),
203
261
  hoistSetup,
204
262
  ...setupFiles
205
263
  ],
@@ -467,6 +525,13 @@ function toViteAliases(resolveAliases, root) {
467
525
  );
468
526
  }
469
527
 
528
+ // The dir a package dir is found from, as Node resolves it - the parent of its node_modules.
529
+ function nodeModulesParent(dir) {
530
+ const parts = dir.split(path.sep),
531
+ idx = parts.lastIndexOf('node_modules');
532
+ return idx > 0 ? parts.slice(0, idx).join(path.sep) : path.dirname(dir);
533
+ }
534
+
470
535
  // A directory path in posix form with a trailing slash, for prefix matches against Vite ids.
471
536
  function dirPrefix(p) {
472
537
  return p.split(path.sep).join('/').replace(/\/?$/, '/');
package/lib/common.js CHANGED
@@ -17,6 +17,7 @@ const _ = require('lodash'),
17
17
  path = require('path'),
18
18
  fs = require('fs'),
19
19
  crypto = require('crypto'),
20
+ {execFileSync} = require('child_process'),
20
21
  parseChangelogMarkdown = require('changelog-parser').parseChangelog,
21
22
  devUtilsPkg = require('../package');
22
23
 
@@ -67,6 +68,31 @@ function checkHoistReactVersion(hoistReactPkg, inlineHoist) {
67
68
  }
68
69
  }
69
70
 
71
+ // Rspack releases that break Hoist builds, each with the reason and the fix for that release. A
72
+ // published version never changes, so blocking an exact version is permanent and safe.
73
+ const BLOCKED_RSPACK_VERSIONS = {
74
+ '2.3.2':
75
+ 'Its minifier breaks classes that reference themselves in a static initializer when ' +
76
+ 'keep_classnames is set, so production builds crash on load ' +
77
+ '(web-infra-dev/rspack#16586). Use 2.3.0 until a fixed release ships - see ' +
78
+ 'xh/hoist-dev-utils#85.'
79
+ };
80
+
81
+ /**
82
+ * Fail the build, or the dev server, on an Rspack release known to break Hoist builds. The dev
83
+ * server fails too, even where it would run, so the problem shows up on the first local run rather
84
+ * than in a production build.
85
+ */
86
+ function checkRspackVersion(rspackVersion) {
87
+ const detail = BLOCKED_RSPACK_VERSIONS[rspackVersion];
88
+ if (detail) {
89
+ throw (
90
+ `@rspack/core v${rspackVersion} is not supported by hoist-dev-utils - pin a ` +
91
+ `supported version with a pnpm override in the app. ${detail}`
92
+ );
93
+ }
94
+ }
95
+
70
96
  /**
71
97
  * True if `version` is below a 'major[.minor]' minimum. Any suffix (`-SNAPSHOT.<ts>`) is ignored,
72
98
  * and a version with no numeric major (e.g. 'NOT_FOUND') is never below.
@@ -392,6 +418,7 @@ const KNOWN_OPTIONS = [
392
418
  'appBuild',
393
419
  'prodBuild',
394
420
  'inlineHoist',
421
+ 'inlinePackages',
395
422
  'reactProdMode',
396
423
  'sourceMaps',
397
424
  'targetBrowsers',
@@ -452,6 +479,24 @@ function logSep() {
452
479
  console.log(':------------------------------------');
453
480
  }
454
481
 
482
+ /**
483
+ * The branch checked out at `dir`, a short commit hash if HEAD is detached, or null if `dir` is not
484
+ * a git checkout or git is not available. Used to show which code an inline build runs against.
485
+ */
486
+ function gitBranch(dir) {
487
+ const git = args =>
488
+ execFileSync('git', ['-C', dir, ...args], {
489
+ encoding: 'utf8',
490
+ stdio: 'pipe',
491
+ timeout: 5000
492
+ }).trim();
493
+ try {
494
+ return git(['branch', '--show-current']) || git(['rev-parse', '--short', 'HEAD']);
495
+ } catch (e) {
496
+ return null;
497
+ }
498
+ }
499
+
455
500
  function logMsg(msg) {
456
501
  console.log(`: ${msg}`);
457
502
  }
@@ -466,6 +511,7 @@ module.exports = {
466
511
  resolveAppPackage,
467
512
  isVersionBelow,
468
513
  checkHoistReactVersion,
514
+ checkRspackVersion,
469
515
  resolveIcons,
470
516
  writeChangelogJson,
471
517
  checkNoJsxFiles,
@@ -478,6 +524,7 @@ module.exports = {
478
524
  generateBlueprintIconStubs,
479
525
  findJsxFiles,
480
526
  safeRealpath,
527
+ gitBranch,
481
528
  parseFlag,
482
529
  warnUnknownOptions,
483
530
  logSep,
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  const _ = require('lodash'),
16
+ fs = require('fs'),
16
17
  path = require('path'),
17
18
  {safeRealpath} = require('./common');
18
19
 
@@ -92,16 +93,42 @@ const INLINE_HOIST_SINGLETONS = Object.freeze([
92
93
  ]);
93
94
 
94
95
  /**
95
- * Locate hoist-react - a sibling checkout at `../../hoist-react` in inline mode, otherwise the
96
- * installed package. Symlinks are resolved (a no-op for flat layouts) so the path matches the real
97
- * module paths bundlers produce, as include rules need under pnpm.
96
+ * The environment variable that points inline mode at a specific hoist-react checkout, e.g. a git
97
+ * worktree on a paired feature branch. Must be an absolute path.
98
98
  */
99
- function resolveHoistPath(basePath, inlineHoist) {
100
- return safeRealpath(
101
- inlineHoist
102
- ? path.resolve(basePath, '../../hoist-react')
103
- : path.resolve(basePath, 'node_modules/@xh/hoist')
104
- );
99
+ const HOIST_REACT_PATH_VAR = 'XH_HOIST_REACT_PATH';
100
+
101
+ /**
102
+ * Locate hoist-react. In inline mode, this is the checkout named by `XH_HOIST_REACT_PATH`, else a
103
+ * sibling of the app's repo at `../../hoist-react`. Inline mode fails fast unless the path holds a
104
+ * hoist-react checkout. Otherwise, this is the installed package. Symlinks are resolved (a no-op for
105
+ * flat layouts) so the path matches the real module paths bundlers produce, as include rules need
106
+ * under pnpm.
107
+ */
108
+ function resolveHoistPath(basePath, inlineHoist, processEnv = process.env) {
109
+ if (!inlineHoist) return safeRealpath(path.resolve(basePath, 'node_modules/@xh/hoist'));
110
+
111
+ const override = processEnv[HOIST_REACT_PATH_VAR];
112
+ if (override && !path.isAbsolute(override)) {
113
+ throw `${HOIST_REACT_PATH_VAR} must be an absolute path - found "${override}".`;
114
+ }
115
+
116
+ const hoistPath = safeRealpath(override || path.resolve(basePath, '../../hoist-react'));
117
+ if (readPackageName(hoistPath) !== '@xh/hoist') {
118
+ throw override
119
+ ? `${HOIST_REACT_PATH_VAR} points at ${hoistPath}, which is not a hoist-react checkout.`
120
+ : `Inline Hoist found no hoist-react checkout at ${hoistPath}. Clone hoist-react ` +
121
+ `there, or set ${HOIST_REACT_PATH_VAR} to the checkout to use.`;
122
+ }
123
+ return hoistPath;
124
+ }
125
+
126
+ function readPackageName(dir) {
127
+ try {
128
+ return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).name;
129
+ } catch (e) {
130
+ return null;
131
+ }
105
132
  }
106
133
 
107
134
  module.exports = {
@@ -110,5 +137,6 @@ module.exports = {
110
137
  resolveAppIdentity,
111
138
  xhDefines,
112
139
  INLINE_HOIST_SINGLETONS,
140
+ HOIST_REACT_PATH_VAR,
113
141
  resolveHoistPath
114
142
  };
@@ -0,0 +1,267 @@
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
+ /**
10
+ * Inline mode: run local checkouts in place of installed packages - hoist-react under `inlineHoist`,
11
+ * and Hoist companion packages (e.g. `@xh/hoist-chat-kit`, `@xh/package-template` or a client's own
12
+ * overlay on hoist-react) under `inlinePackages`. `configureRsbuild()` and `configureVitest()` both
13
+ * build on the plan made here. `resolveHoistPath()` in `lib/hoistCompile.js` still finds the
14
+ * hoist-react checkout, as the build uses that path well beyond module resolution. No bundler API,
15
+ * as for `lib/common.js`.
16
+ *
17
+ * A checkout has its own node_modules, holding its peers (`@xh/hoist`, React) as devDependencies.
18
+ * Resolved from there, they would load a second Hoist and a second React into the app. So every
19
+ * peer of an inline package, plus `@xh/hoist` and the inline Hoist singletons, is "shared": the
20
+ * plan maps each to one directory that every importer gets. The package's own dependencies still
21
+ * resolve from its checkout, as its lockfile lays them out.
22
+ */
23
+
24
+ const _ = require('lodash'),
25
+ path = require('path'),
26
+ fs = require('fs'),
27
+ semver = require('semver'),
28
+ {safeRealpath} = require('./common'),
29
+ {INLINE_HOIST_SINGLETONS} = require('./hoistCompile');
30
+
31
+ /** Lists the packages to run inline, as `name` or `name=/abs/path`, comma-separated. */
32
+ const INLINE_PACKAGES_VAR = 'XH_INLINE_PACKAGES';
33
+
34
+ const HOIST = '@xh/hoist';
35
+
36
+ /**
37
+ * Parse inline package specs from the `inlinePackages` option or `XH_INLINE_PACKAGES`: a
38
+ * comma-separated string or an array, each entry `name` or `name=/abs/path`.
39
+ * @returns {{name: string, path: ?string}[]}
40
+ */
41
+ function parseInlinePackages(val) {
42
+ // 'false' arrives raw from the env var in tests - the build's readCliEnv() parses it first.
43
+ if (val == null || val === false || val === '' || val === 'false') return [];
44
+ const entries = _.isString(val) ? val.split(',') : _.castArray(val);
45
+ if (!entries.every(_.isString)) {
46
+ throw `inlinePackages takes package names, as "name" or "name=/abs/path".`;
47
+ }
48
+
49
+ const ret = [];
50
+ entries
51
+ .map(it => it.trim())
52
+ .filter(Boolean)
53
+ .forEach(entry => {
54
+ // Split at the first '=' - a scoped name holds no '=', a path may.
55
+ const idx = entry.indexOf('='),
56
+ name = (idx < 0 ? entry : entry.slice(0, idx)).trim(),
57
+ dir = idx < 0 ? null : entry.slice(idx + 1).trim();
58
+
59
+ if (!name) throw `inlinePackages entry "${entry}" has no package name.`;
60
+ if (dir === '') throw `inlinePackages entry "${entry}" has an empty path.`;
61
+ if (name === HOIST || name.startsWith(HOIST + '/')) {
62
+ throw `inlinePackages cannot hold ${HOIST} - use inlineHoist for hoist-react.`;
63
+ }
64
+ if (dir && !path.isAbsolute(dir)) {
65
+ throw `inlinePackages path for ${name} must be absolute - found "${dir}".`;
66
+ }
67
+ if (ret.some(it => it.name === name)) {
68
+ throw `inlinePackages lists ${name} more than once.`;
69
+ }
70
+ ret.push({name, path: dir});
71
+ });
72
+ return ret;
73
+ }
74
+
75
+ /**
76
+ * Plan inline mode: locate each package checkout, then pick one directory for each shared name.
77
+ * Plans nothing when neither Hoist nor any package is inline. Throws, before the build logs
78
+ * anything, when a checkout or a required peer is missing. Returns warnings for the caller to log.
79
+ *
80
+ * @param {Object} opts
81
+ * @param {string} opts.appRoot - the app's root dir (client-app), a real path.
82
+ * @param {{name: string, path: ?string}[]} opts.specs - from `parseInlinePackages()`.
83
+ * @param {string} opts.hoistPath - hoist-react's real path, inline checkout or installed.
84
+ * @param {boolean} opts.inlineHoist - true when hoistPath is an inline checkout.
85
+ * @param {string[]} [opts.extraSingletons] - more names to share when the app has them.
86
+ * @returns {{packages: Object[], shared: Object[], warnings: string[]}} - `packages` holds
87
+ * `{name, path, nodeModules, pkg}` per checkout, `shared` holds `{name, dir, source}` per
88
+ * shared name, where source is 'inline' (a checkout), 'app' or 'hoist' (Hoist's own copy, for
89
+ * a transitive peer the app does not install).
90
+ */
91
+ function planInlinePackages({appRoot, specs, hoistPath, inlineHoist, extraSingletons = []}) {
92
+ const warnings = [],
93
+ packages = specs.map(spec => locatePackage(appRoot, spec));
94
+ if (!packages.length && !inlineHoist) return {packages, shared: [], warnings};
95
+
96
+ // Checkouts first - an import of an inline name always goes to its checkout.
97
+ const inlineDirs = new Map(packages.map(p => [p.name, p.path]));
98
+ if (inlineHoist) inlineDirs.set(HOIST, hoistPath);
99
+
100
+ const shared = new Map();
101
+ const share = (name, dir, source) => shared.set(name, {name, dir, source});
102
+ inlineDirs.forEach((dir, name) => share(name, dir, 'inline'));
103
+
104
+ // Hoist is a singleton whether or not it is inline - it is our `hoistPath` either way.
105
+ if (!shared.has(HOIST)) share(HOIST, hoistPath, 'app');
106
+
107
+ // Peers. A required peer must resolve, an optional one is shared only when found.
108
+ packages.forEach(({name, pkg}) => {
109
+ const optional = pkg.peerDependenciesMeta ?? {};
110
+ Object.keys(pkg.peerDependencies ?? {}).forEach(peer => {
111
+ if (shared.has(peer)) return;
112
+ const found = findSharedCopy(peer, appRoot, hoistPath);
113
+ if (found) return share(peer, found.dir, found.source);
114
+ if (optional[peer]?.optional) return;
115
+ throw (
116
+ `Inline package ${name} needs peer "${peer}", which was not found in ` +
117
+ `${path.join(appRoot, 'node_modules')} or from ${hoistPath}. Add "${peer}" ` +
118
+ `to the app's dependencies.`
119
+ );
120
+ });
121
+ });
122
+
123
+ // Singletons, when the app installs them itself. Unlike a peer, a singleton the app lacks is
124
+ // not one the app loads, so the checkouts' copies serve it.
125
+ [...INLINE_HOIST_SINGLETONS, ...extraSingletons].forEach(name => {
126
+ const dir = shared.has(name) ? null : findInAppNodeModules(name, appRoot);
127
+ if (dir) share(name, dir, 'app');
128
+ });
129
+
130
+ packages.forEach(p => warnings.push(...checkPackage(p, shared, appRoot)));
131
+ return {packages, shared: [...shared.values()], warnings};
132
+ }
133
+
134
+ /**
135
+ * The keys of an app's `resolveAliases` that name a shared package - `react` or `react$`. The plan
136
+ * replaces them, so a hand-written alias to a checkout from before inline packages stops applying.
137
+ */
138
+ function replacedAppAliases(resolveAliases, shared) {
139
+ const names = new Set(shared.map(it => it.name));
140
+ return Object.keys(resolveAliases ?? {}).filter(key => names.has(key.replace(/\$$/, '')));
141
+ }
142
+
143
+ /**
144
+ * Add the inline settings to a `buildCache` config's `cacheDigest`, keeping any digest the app
145
+ * passed. Rsbuild keys the persistent cache on that digest, so a run with other inline settings
146
+ * gets a cache of its own, not snapshots that resolve to the wrong copy. A build cache that is off,
147
+ * or a run with nothing inline, is returned as passed.
148
+ */
149
+ function withInlineCacheDigest(buildCache, {inlineHoist, hoistPath, packages}) {
150
+ const digest = [
151
+ ...(inlineHoist ? [`inlineHoist:${hoistPath}`] : []),
152
+ ...packages.map(it => `inlinePackage:${it.name}=${it.path}`)
153
+ ];
154
+ if (!buildCache || !digest.length) return buildCache;
155
+
156
+ const config = _.isPlainObject(buildCache) ? buildCache : {};
157
+ return {...config, cacheDigest: [...(config.cacheDigest ?? []), ...digest]};
158
+ }
159
+
160
+ //------------------------
161
+ // Implementation
162
+ //------------------------
163
+ function locatePackage(appRoot, {name, path: explicitPath}) {
164
+ // Default to a sibling of the app's repo, named for the package without its scope - as
165
+ // hoist-react's default checkout is `../../hoist-react`.
166
+ const dir = safeRealpath(explicitPath || path.resolve(appRoot, '../..', name.split('/').pop())),
167
+ pkg = readJson(path.join(dir, 'package.json'));
168
+
169
+ if (!pkg) {
170
+ throw explicitPath
171
+ ? `Inline package ${name} points at ${dir}, which holds no package.json.`
172
+ : `Inline package ${name} found no checkout at ${dir}. Clone it there, or pass its ` +
173
+ `path as "${name}=/abs/path" in ${INLINE_PACKAGES_VAR}.`;
174
+ }
175
+ if (pkg.name !== name) {
176
+ throw `Inline package ${name} points at ${dir}, which holds "${pkg.name}" instead.`;
177
+ }
178
+ // Its dependencies resolve from the checkout, so they must be installed there. Peers come
179
+ // from the app, so a package with none of its own needs no install.
180
+ const nodeModules = path.join(dir, 'node_modules');
181
+ if (!_.isEmpty(pkg.dependencies) && !fs.existsSync(nodeModules)) {
182
+ throw (
183
+ `Inline package ${name} at ${dir} has no node_modules - install its dependencies ` +
184
+ `there first (e.g. \`pnpm install\`).`
185
+ );
186
+ }
187
+ return {name, path: dir, nodeModules, pkg};
188
+ }
189
+
190
+ /**
191
+ * The copy of a shared name that every importer gets: the app's own, else the one Hoist loads -
192
+ * e.g. MobX, which an app takes through `@xh/hoist/mobx` and does not install itself. The app's
193
+ * copy must be in its own node_modules, as for singletons - a stray copy above the app is one
194
+ * Hoist does not load.
195
+ */
196
+ function findSharedCopy(name, appRoot, hoistPath) {
197
+ const appDir = findInAppNodeModules(name, appRoot);
198
+ if (appDir) return {dir: appDir, source: 'app'};
199
+ const hoistDir = findInNodeModules(name, hoistPath);
200
+ return hoistDir ? {dir: hoistDir, source: 'hoist'} : null;
201
+ }
202
+
203
+ /** A package in the app's own node_modules, by its real path, or null. */
204
+ function findInAppNodeModules(name, appRoot) {
205
+ const dir = path.join(appRoot, 'node_modules', name);
206
+ return fs.existsSync(path.join(dir, 'package.json')) ? safeRealpath(dir) : null;
207
+ }
208
+
209
+ /**
210
+ * Find a package's directory as Node would from `fromDir` - each node_modules up the tree - by its
211
+ * package.json. A plain lookup, as `require.resolve('x/package.json')` fails on packages whose
212
+ * `exports` field hides their package.json. Returns the real path, or null.
213
+ */
214
+ function findInNodeModules(name, fromDir) {
215
+ for (let dir = fromDir; ; dir = path.dirname(dir)) {
216
+ const candidate = path.join(dir, 'node_modules', name);
217
+ if (fs.existsSync(path.join(candidate, 'package.json'))) return safeRealpath(candidate);
218
+ if (path.dirname(dir) === dir) return null;
219
+ }
220
+ }
221
+
222
+ /** Warnings for one inline package: app pairing, peer ranges and misplaced dependencies. */
223
+ function checkPackage({name, pkg}, shared, appRoot) {
224
+ const ret = [],
225
+ appPkg = readJson(path.join(appRoot, 'package.json')) ?? {};
226
+
227
+ if (!appPkg.dependencies?.[name] && !appPkg.devDependencies?.[name]) {
228
+ ret.push(`${name} is not in the app's package.json - running it inline anyway.`);
229
+ }
230
+
231
+ // Warn only - a mismatch may be deliberate mid-way through a paired upgrade. Prereleases count,
232
+ // or every Hoist snapshot would fail a plain floor such as ">=89.3.1".
233
+ _.forEach(pkg.peerDependencies, (range, peer) => {
234
+ const dir = shared.get(peer)?.dir,
235
+ version = dir && readJson(path.join(dir, 'package.json'))?.version;
236
+ if (!version || !semver.validRange(range)) return;
237
+ if (!semver.satisfies(version, range, {includePrerelease: true})) {
238
+ ret.push(`${name} wants ${peer} "${range}", but the app will run ${version}.`);
239
+ }
240
+ });
241
+
242
+ // A shared name under `dependencies` still gets the shared copy here, but an install from npm
243
+ // gives the package its own - declare it a peer so both agree. Other @xh packages are flagged
244
+ // too: a second copy of a companion package would not be shared.
245
+ Object.keys(pkg.dependencies ?? {}).forEach(dep => {
246
+ if (shared.has(dep) || dep.startsWith('@xh/')) {
247
+ ret.push(`${name} lists "${dep}" in dependencies - it should be a peerDependency.`);
248
+ }
249
+ });
250
+ return ret;
251
+ }
252
+
253
+ function readJson(file) {
254
+ try {
255
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
256
+ } catch (e) {
257
+ return null;
258
+ }
259
+ }
260
+
261
+ module.exports = {
262
+ INLINE_PACKAGES_VAR,
263
+ parseInlinePackages,
264
+ planInlinePackages,
265
+ replacedAppAliases,
266
+ withInlineCacheDigest
267
+ };
@@ -6,15 +6,20 @@
6
6
  */
7
7
 
8
8
  /**
9
- * First setup file of an inline-hoist test run, added by `configureVitest()`.
9
+ * First setup file of an inline test run - inline Hoist, inline packages or both - added by
10
+ * `configureVitest()`.
10
11
  *
11
- * Vite's `resolve.dedupe` reaches only the modules Vite resolves. Vitest externalizes the
12
- * checkout's own dependencies (e.g. mobx-react-lite, Blueprint, ag-grid-react), so Node loads them
13
- * and resolves their `react` from the checkout's node_modules - a second React, and hooks fail.
14
- * This hook sends those imports to the app's copies instead, as the build's aliases do.
12
+ * Vite's `resolve.dedupe` and aliases reach only the modules Vite resolves. Vitest externalizes a
13
+ * checkout's own dependencies (e.g. mobx-react-lite, Blueprint, ag-grid-react, @ag-ui/client), so
14
+ * Node loads them and resolves their `react` from the checkout's node_modules - a second React,
15
+ * and hooks fail. This hook sends imports of each shared name made from a checkout's node_modules
16
+ * to the one copy the build uses, as the build's aliases do. A shared name that is itself a
17
+ * checkout (`@xh/hoist` under inline Hoist) is not redirected - a library a checkout installs does
18
+ * not import its host.
15
19
  *
16
- * Settings arrive in `XH_VITEST_INLINE_HOIST_CFG`, set by `configureVitest()`.
17
- * `module.registerHooks()` needs Node >= 22.15.
20
+ * Settings arrive in `XH_VITEST_INLINE_HOIST_CFG`, set by `configureVitest()`: `fromDirs`, the
21
+ * checkouts' node_modules dirs, and `singletons`, each `{name, from}` with the dir to resolve that
22
+ * name from. `module.registerHooks()` needs Node >= 22.15.
18
23
  */
19
24
  import {createRequire, registerHooks} from 'node:module';
20
25
  import path from 'node:path';
@@ -22,25 +27,37 @@ import {pathToFileURL} from 'node:url';
22
27
 
23
28
  const cfg = JSON.parse(process.env.XH_VITEST_INLINE_HOIST_CFG ?? 'null');
24
29
 
25
- if (cfg?.singletons?.length) {
26
- const fromUrl = pathToFileURL(path.join(cfg.hoistNodeModules, '/')).href,
27
- appParentUrl = pathToFileURL(path.join(cfg.appRoot, 'package.json')).href,
28
- appRequire = createRequire(appParentUrl),
29
- names = cfg.singletons.map(it => it.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|'),
30
- singletonRe = new RegExp(`^(?:${names})(?:/|$)`);
30
+ if (cfg?.singletons?.length && cfg.fromDirs?.length) {
31
+ const fromUrls = cfg.fromDirs.map(it => pathToFileURL(path.join(it, '/')).href),
32
+ escape = it => it.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'),
33
+ targets = cfg.singletons.map(({name, from}) => {
34
+ const parentUrl = pathToFileURL(path.join(from, 'package.json')).href;
35
+ return {
36
+ re: new RegExp(`^${escape(name)}(?:/|$)`),
37
+ parentUrl,
38
+ require: createRequire(parentUrl)
39
+ };
40
+ });
31
41
 
32
42
  registerHooks({
33
43
  resolve(specifier, context, nextResolve) {
34
- if (!singletonRe.test(specifier) || !context.parentURL?.startsWith(fromUrl)) {
35
- return nextResolve(specifier, context);
36
- }
37
- // An ESM import resolves from the app with its own conditions, so it still gets a
38
- // package's ESM build (ag-Grid ships both). A changed parentURL does not redirect a
39
- // CJS require(), so that resolves through the app's require instead.
44
+ const parent = context.parentURL,
45
+ target =
46
+ parent && fromUrls.some(it => parent.startsWith(it))
47
+ ? targets.find(it => it.re.test(specifier))
48
+ : null;
49
+ if (!target) return nextResolve(specifier, context);
50
+
51
+ // An ESM import resolves from the shared copy's location with its own conditions, so
52
+ // it still gets a package's ESM build (ag-Grid ships both). A changed parentURL does
53
+ // not redirect a CJS require(), so that resolves through a require from there instead.
40
54
  if (context.conditions?.includes('import')) {
41
- return nextResolve(specifier, {...context, parentURL: appParentUrl});
55
+ return nextResolve(specifier, {...context, parentURL: target.parentUrl});
42
56
  }
43
- return {url: pathToFileURL(appRequire.resolve(specifier)).href, shortCircuit: true};
57
+ return {
58
+ url: pathToFileURL(target.require.resolve(specifier)).href,
59
+ shortCircuit: true
60
+ };
44
61
  }
45
62
  });
46
63
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xh/hoist-dev-utils",
3
- "version": "16.2.0",
3
+ "version": "16.4.0",
4
4
  "description": "Rsbuild (Rspack + SWC) build configuration and shared dev dependencies for Hoist React applications.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,11 +35,12 @@
35
35
  "@xh/eslint-config": "^8.1.0",
36
36
  "changelog-parser": "~4.1.0",
37
37
  "lodash": "^4.18.1",
38
- "sass-embedded": "^1.107.1",
38
+ "sass-embedded": "^1.108.2",
39
+ "semver": "^7.8.5",
39
40
  "type-fest": "^5.10.0"
40
41
  },
41
42
  "devDependencies": {
42
- "prettier": "^3.9.10"
43
+ "prettier": "^3.10.1"
43
44
  },
44
45
  "packageManager": "pnpm@12.10.1+sha512.ba40a37eb1a370d60fea8c4cf1d364c13bcccef518e98ad2bcee954f539d38da37458e58261a3fa55e06523450ea0ffff9f497b135be41f2c15c1642bacace6c"
45
46
  }