cabloy 5.1.218 → 5.1.220

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 (66) hide show
  1. package/.cabloy-version +1 -1
  2. package/.github/workflows/create-cabloy.yml +1 -1
  3. package/CHANGELOG.md +19 -0
  4. package/README.md +1 -1
  5. package/package.json +1 -1
  6. package/repo-docs/fullstack/quickstart.md +3 -3
  7. package/repo-docs/reference/repo-scripts.md +12 -0
  8. package/scripts/generateOpenapiIsolated.test.ts +25 -0
  9. package/scripts/generateOpenapiIsolated.ts +28 -11
  10. package/scripts/runIsolatedTest.test.ts +157 -45
  11. package/scripts/runIsolatedTest.ts +30 -6
  12. package/scripts/strictGenerationStartup.test.ts +212 -0
  13. package/vona/packages-cli/cli/package.json +1 -1
  14. package/vona/packages-cli/cli-set-api/package.json +1 -1
  15. package/vona/packages-vona/vona/package.json +1 -1
  16. package/vona/packages-vona/vona-core/package.json +1 -1
  17. package/vona/packages-vona/vona-core/src/lib/bean/beanBase.ts +4 -0
  18. package/vona/packages-vona/vona-core/src/lib/core/asyncLocalStorage.ts +84 -12
  19. package/vona/packages-vona/vona-core/src/lib/core/index.ts +14 -0
  20. package/vona/packages-vona/vona-core/src/lib/core/logger/appLogger.ts +11 -3
  21. package/vona/packages-vona/vona-core/src/lib/core/logger/diagnosticLogger.test.ts +146 -0
  22. package/vona/packages-vona/vona-core/src/lib/core/logger/diagnosticLogger.ts +138 -0
  23. package/vona/packages-vona/vona-core/src/lib/core/logger/index.ts +1 -0
  24. package/vona/packages-vona/vona-core/src/lib/core/logger/utils.ts +25 -5
  25. package/vona/packages-vona/vona-core/src/lib/core/requestBoundary.ts +89 -0
  26. package/vona/packages-vona/vona-core/src/lib/core/testFreshness.test.ts +379 -0
  27. package/vona/packages-vona/vona-core/src/lib/core/testFreshness.ts +238 -0
  28. package/vona/packages-vona/vona-core/src/lib/framework/start.test.ts +4 -3
  29. package/vona/packages-vona/vona-core/src/lib/framework/start.ts +2 -0
  30. package/vona/packages-vona/vona-mock/package.json +1 -1
  31. package/vona/pnpm-lock.yaml +218 -43
  32. package/vona/pnpm-workspace.yaml +1 -1
  33. package/vona/src/suite-vendor/a-vona/modules/a-core/package.json +1 -1
  34. package/vona/src/suite-vendor/a-vona/modules/a-executor/package.json +1 -1
  35. package/vona/src/suite-vendor/a-vona/modules/a-executor/src/bean/bean.executor.ts +111 -60
  36. package/vona/src/suite-vendor/a-vona/modules/a-executor/src/service/executor.ts +6 -6
  37. package/vona/src/suite-vendor/a-vona/modules/a-executor/src/types/executor.ts +13 -1
  38. package/vona/src/suite-vendor/a-vona/modules/a-jwt/package.json +1 -1
  39. package/vona/src/suite-vendor/a-vona/modules/a-jwt/src/lib/jwtClientLogging.test.ts +182 -0
  40. package/vona/src/suite-vendor/a-vona/modules/a-jwt/src/service/jwtClient.ts +2 -8
  41. package/vona/src/suite-vendor/a-vona/modules/a-logger/package.json +1 -1
  42. package/vona/src/suite-vendor/a-vona/modules/a-logger/src/bean/aopMethod.log.ts +4 -1
  43. package/vona/src/suite-vendor/a-vona/modules/a-logger/src/bean/bean.logger.ts +9 -0
  44. package/vona/src/suite-vendor/a-vona/modules/a-logger/src/bean/middlewareSystem.httpLog.ts +27 -14
  45. package/vona/src/suite-vendor/a-vona/modules/a-logger/src/lib/redactHttpLog.test.ts +207 -0
  46. package/vona/src/suite-vendor/a-vona/modules/a-logger/src/lib/redactHttpLog.ts +30 -0
  47. package/vona/src/suite-vendor/a-vona/modules/a-logger/test/middlewareSystem.httpLog.test.ts +33 -1
  48. package/vona/src/suite-vendor/a-vona/modules/a-startup/package.json +1 -1
  49. package/vona/src/suite-vendor/a-vona/modules/a-startup/src/service/startup.ts +6 -0
  50. package/vona/src/suite-vendor/a-vona/modules/a-startup/test/devSeed.test.ts +2 -2
  51. package/vona/src/suite-vendor/a-vona/modules/a-telemetry/package.json +1 -1
  52. package/vona/src/suite-vendor/a-vona/modules/a-telemetry/src/bean/bean.telemetry.ts +8 -1
  53. package/vona/src/suite-vendor/a-vona/modules/a-telemetry/src/bean/middlewareSystem.trace.ts +9 -14
  54. package/vona/src/suite-vendor/a-vona/modules/a-telemetry/src/lib/spanDiagnostics.ts +70 -0
  55. package/vona/src/suite-vendor/a-vona/modules/a-telemetry/src/service/telemetry.ts +37 -23
  56. package/vona/src/suite-vendor/a-vona/modules/a-version/package.json +1 -1
  57. package/vona/src/suite-vendor/a-vona/modules/a-version/src/service/database.ts +31 -4
  58. package/vona/src/suite-vendor/a-vona/package.json +2 -2
  59. package/zova/packages-cli/cli/package.json +2 -2
  60. package/zova/packages-cli/cli-set-front/package.json +1 -1
  61. package/zova/packages-cli/cli-set-front/src/lib/bean/cli.bin.buildRest.ts +11 -101
  62. package/zova/packages-cli/cli-set-front/src/lib/common/restDependencies.ts +78 -0
  63. package/zova/packages-cli/cli-set-front/src/lib/common/restDependencyVersions.ts +231 -0
  64. package/zova/packages-cli/cli-set-front/test/restDependencies.test.ts +431 -0
  65. package/zova/pnpm-lock.yaml +8 -8
  66. /package/vona/patches/{zova-core@5.1.92.patch → zova-core@5.1.93.patch} +0 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vona-module-a-version",
3
- "version": "5.1.21",
3
+ "version": "5.1.22",
4
4
  "gitHead": "a79189b882c17af5911573896a781bbb0046d37d",
5
5
  "description": "vona-module-a-version",
6
6
  "keywords": [
@@ -9,6 +9,8 @@ import {
9
9
  BeanBase,
10
10
  assertDisposableDatabaseName as assertDisposableDatabaseNameCore,
11
11
  assertIsolatedTestPath,
12
+ assertFreshTestResourcesReady,
13
+ requiresFreshTestResources,
12
14
  assertTestRunOwner,
13
15
  resolveVonaLocalPaths,
14
16
  withIsolatedTestDatabaseDiscovery,
@@ -39,6 +41,7 @@ interface IDevDatabasePreparation {
39
41
  }
40
42
 
41
43
  const devDatabasePreparations = new WeakMap<VonaApplication, IDevDatabasePreparation>();
44
+ const freshDatabaseCreations = new WeakMap<VonaApplication, Map<string, string>>();
42
45
 
43
46
  export function assertDisposableDatabaseName(
44
47
  databaseName: string,
@@ -318,7 +321,7 @@ export class ServiceDatabase extends BeanBase {
318
321
  // client
319
322
  const client = this.bean.database.current.client;
320
323
  // get current database name
321
- const databaseName = client.getDatabaseName();
324
+ const currentDatabaseName = client.getDatabaseName();
322
325
  const sqliteRoot =
323
326
  client.db.dialectName === 'better-sqlite3'
324
327
  ? resolveVonaLocalPaths(
@@ -327,9 +330,12 @@ export class ServiceDatabase extends BeanBase {
327
330
  this.app.meta.env.VONA_TEST_RUN_ID,
328
331
  ).sqliteRoot
329
332
  : undefined;
330
- const currentFilename = sqliteRoot ? path.basename(databaseName, '.db') : databaseName;
333
+ const currentFilename = sqliteRoot
334
+ ? path.basename(currentDatabaseName, '.db')
335
+ : currentDatabaseName;
331
336
  const isTestDatabase = currentFilename.startsWith(databasePrefix);
332
- if (isTestDatabase) assertDisposableDatabaseName(databaseName, databasePrefix, sqliteRoot);
337
+ if (isTestDatabase)
338
+ assertDisposableDatabaseName(currentDatabaseName, databasePrefix, sqliteRoot);
333
339
  if (
334
340
  this.app.meta.isTest &&
335
341
  this.app.meta.env.VONA_TEST_RUN_ID &&
@@ -337,11 +343,32 @@ export class ServiceDatabase extends BeanBase {
337
343
  !isTestDatabase
338
344
  ) {
339
345
  throw new Error(
340
- `Isolated test database is outside its disposable namespace: ${databaseName}`,
346
+ `Isolated test database is outside its disposable namespace: ${currentDatabaseName}`,
341
347
  );
342
348
  }
343
349
  // test db
344
350
  if (this.app.meta.isTest) {
351
+ if (requiresFreshTestResources()) {
352
+ assertFreshTestResourcesReady(this.app);
353
+ const key = `${client.clientName}\0${databasePrefix}`;
354
+ const created = freshDatabaseCreations.get(this.app);
355
+ if (isTestDatabase) {
356
+ if (created?.get(key) !== currentDatabaseName) {
357
+ throw new Error('Strict test cannot reuse an unowned database');
358
+ }
359
+ return;
360
+ }
361
+ if ((await this.__fetchDatabases(client, instanceName, configInstanceBase)).length !== 0) {
362
+ throw new Error('Strict test database namespace is no longer fresh');
363
+ }
364
+ const name = await this.__createDatabase(client, instanceName, configInstanceBase);
365
+ assertDisposableDatabaseName(name, databasePrefix, sqliteRoot);
366
+ const creations = created ?? new Map<string, string>();
367
+ creations.set(key, name);
368
+ freshDatabaseCreations.set(this.app, creations);
369
+ await client.changeConfigConnectionAndReloadWorker(name);
370
+ return;
371
+ }
345
372
  // check
346
373
  if (isTestDatabase) {
347
374
  // donothing
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vona-suite-a-vona",
3
- "version": "5.1.101",
3
+ "version": "5.1.102",
4
4
  "gitHead": "a79189b882c17af5911573896a781bbb0046d37d",
5
5
  "description": "",
6
6
  "author": "",
@@ -54,7 +54,7 @@
54
54
  "vona-module-a-static": "workspace:^",
55
55
  "vona-module-a-summer": "workspace:^",
56
56
  "vona-module-a-swagger": "workspace:^",
57
- "vona-module-a-telemetry": "^5.0.2",
57
+ "vona-module-a-telemetry": "^5.0.3",
58
58
  "vona-module-a-upload": "workspace:^",
59
59
  "vona-module-a-user": "workspace:^",
60
60
  "vona-module-a-validation": "workspace:^",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zova-cli",
3
- "version": "1.2.115",
3
+ "version": "1.2.116",
4
4
  "gitHead": "6f675a8cc46d596142c591c28a40cc4d82fcc6cc",
5
5
  "description": "zova cli",
6
6
  "keywords": [
@@ -44,7 +44,7 @@
44
44
  "@cabloy/process-helper": "^3.1.8",
45
45
  "fs-extra": "^11.3.5",
46
46
  "semver": "^7.6.2",
47
- "zova-cli-set-front": "^1.2.113"
47
+ "zova-cli-set-front": "^1.2.114"
48
48
  },
49
49
  "devDependencies": {
50
50
  "clean-package": "^2.2.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zova-cli-set-front",
3
- "version": "1.2.113",
3
+ "version": "1.2.114",
4
4
  "gitHead": "6f675a8cc46d596142c591c28a40cc4d82fcc6cc",
5
5
  "description": "zova cli-set-front",
6
6
  "keywords": [
@@ -12,9 +12,10 @@ import fse from 'fs-extra';
12
12
  import path from 'node:path';
13
13
  import { rimraf } from 'rimraf';
14
14
  import { build } from 'tsdown';
15
- import yaml from 'yaml';
16
15
  import { createConfigUtils, saveJSONFile } from 'zova-vite';
17
16
 
17
+ import { extractRestDependencies } from '../common/restDependencies.ts';
18
+ import { extractRestDependencyVersions } from '../common/restDependencyVersions.ts';
18
19
  import { loadJSONFile } from '../common/utils.ts';
19
20
  import { __ThisSetName__ } from '../this.ts';
20
21
 
@@ -61,6 +62,7 @@ interface IBinBuildRestContext {
61
62
  outDir: string;
62
63
  bundleModules?: string[];
63
64
  sideEffectImportModuleNames?: string[];
65
+ moduleRoots?: string[];
64
66
  packageJson?: IBinBuildRestPackageJson;
65
67
  }
66
68
 
@@ -116,11 +118,13 @@ export class CliBinBuildRest extends BeanCliBase {
116
118
  const modules: string[] = [];
117
119
  const bundleModules: string[] = [];
118
120
  const sideEffectImportModuleNames: string[] = [];
121
+ const moduleRoots: string[] = [];
119
122
  for (const module of modulesMeta.modulesArray) {
120
123
  const moduleName = module.info.fullName;
121
124
  modules.push(`import '${moduleName}';`);
122
125
  modules.push(`export * from '${moduleName}';`);
123
126
  const moduleRoot = module.root.replaceAll('\\', '/');
127
+ moduleRoots.push(moduleRoot);
124
128
  if (moduleRoot.includes('/src/module/') || moduleRoot.includes('/src/suite/')) {
125
129
  bundleModules.push(moduleName);
126
130
  } else {
@@ -129,6 +133,7 @@ export class CliBinBuildRest extends BeanCliBase {
129
133
  }
130
134
  context.bundleModules = bundleModules;
131
135
  context.sideEffectImportModuleNames = sideEffectImportModuleNames;
136
+ context.moduleRoots = moduleRoots;
132
137
  argv.Modules = modules.join('\n');
133
138
  // Name/Version
134
139
  argv.Name = bundleName;
@@ -181,8 +186,7 @@ export class CliBinBuildRest extends BeanCliBase {
181
186
  tsconfig: 'tsconfig.rest.json',
182
187
  clean: false,
183
188
  dts: {
184
- // resolve: true,
185
- resolver: 'tsc',
189
+ resolver: 'oxc',
186
190
  tsgo: true,
187
191
  eager: true,
188
192
  tsconfig: 'tsconfig.rest.json',
@@ -213,13 +217,13 @@ export class CliBinBuildRest extends BeanCliBase {
213
217
  }
214
218
 
215
219
  async _build(buildContext: IBinBuildRestContext) {
216
- const { projectPath, flavor, bundleNameCopy, outDir, packageJson } = buildContext;
220
+ const { projectPath, flavor, bundleNameCopy, outDir, packageJson, moduleRoots } = buildContext;
217
221
  // build
218
222
  await this._buildTs(buildContext);
219
223
  await this._buildDts(buildContext);
220
224
  // deps
221
225
  const deps = await _extractDeps(path.join(outDir, 'index.d.mts'));
222
- const depsVersion = await _extractDepsVersion(projectPath, deps);
226
+ const depsVersion = await extractRestDependencyVersions(projectPath, deps, moduleRoots);
223
227
  // package.json
224
228
  const pkgContent = {
225
229
  ...packageJson!,
@@ -256,100 +260,6 @@ function _copyToTarget(
256
260
  }
257
261
 
258
262
  async function _extractDeps(filePath: string): Promise<string[]> {
259
- let content = (await fse.readFile(filePath)).toString();
260
- const pos = content.indexOf('//#region');
261
- content = content.substring(0, pos);
262
- const packageNames = new Set();
263
- const re = /import\s+(?:[\s\S]*?\s+from\s+)?['"]([^'"]+)['"]/g;
264
-
265
- let match: any;
266
- while (true) {
267
- match = re.exec(content);
268
- if (!match) break;
269
- let pkg: string = match[1];
270
- if (pkg.startsWith('.') || pkg.startsWith('/')) continue;
271
- if (pkg.startsWith('@')) {
272
- if (pkg.split('/').length > 2) {
273
- pkg = pkg.split('/').slice(0, 2).join('/');
274
- }
275
- } else {
276
- if (pkg.split('/').length > 1) {
277
- pkg = pkg.split('/').slice(0, 1).join('/');
278
- }
279
- }
280
- packageNames.add(pkg);
281
- }
282
- return Array.from(packageNames).sort() as string[];
283
- }
284
-
285
- async function _extractDepsVersion(
286
- projectPath: string,
287
- deps: string[],
288
- ): Promise<Record<string, string>> {
289
- const lockfilePath = path.join(projectPath, 'pnpm-lock.yaml');
290
- const lockfileContent = (await fse.readFile(lockfilePath)).toString();
291
- const parsedLockfile = yaml.parse(lockfileContent);
292
- const depsVersion: Record<string, string> = {};
293
- for (const dep of deps) {
294
- let dependencyRange = getPackageDependencyRangeFromLock(parsedLockfile, dep);
295
- if (!dependencyRange) {
296
- const version = await getPackageVersionFromNodeModules(projectPath, dep);
297
- dependencyRange = version ? `^${version}` : null;
298
- }
299
- if (!dependencyRange) {
300
- console.warn('dep version not found: ', dep);
301
- continue;
302
- }
303
- depsVersion[dep] = dependencyRange;
304
- }
305
- return depsVersion;
306
- }
307
-
308
- function getPackageDependencyRangeFromLock(
309
- parsedLockfile: any,
310
- packageName: string,
311
- ): string | null {
312
- const importer = parsedLockfile.importers?.['.'];
313
- const sections = ['dependencies', 'devDependencies', 'optionalDependencies'];
314
- for (const section of sections) {
315
- const dependencyRange = getImporterDependencyRange(importer?.[section]?.[packageName]);
316
- if (dependencyRange) return dependencyRange;
317
- }
318
- return null;
319
- }
320
-
321
- function getImporterDependencyRange(
322
- importerDependency: { specifier?: string; version?: string } | undefined,
323
- ): string | null {
324
- if (!importerDependency) return null;
325
-
326
- const specifier = importerDependency.specifier;
327
- if (specifier?.startsWith('npm:')) return specifier;
328
-
329
- const version = normalizeLockfileVersion(importerDependency.version);
330
- if (!version) return null;
331
- return `^${version}`;
332
- }
333
-
334
- function normalizeLockfileVersion(version: string | undefined): string | null {
335
- if (!version) return null;
336
- if (version.startsWith('link:') || version.startsWith('file:')) return null;
337
-
338
- const versionWithoutPeers = version.split('(')[0];
339
- if (!versionWithoutPeers) return null;
340
- if (/^\d/.test(versionWithoutPeers)) return versionWithoutPeers;
341
-
342
- const aliasSeparator = versionWithoutPeers.lastIndexOf('@');
343
- if (aliasSeparator === -1) return null;
344
-
345
- const aliasedVersion = versionWithoutPeers.slice(aliasSeparator + 1);
346
- if (!aliasedVersion || !/^\d/.test(aliasedVersion)) return null;
347
- return aliasedVersion;
348
- }
349
-
350
- async function getPackageVersionFromNodeModules(projectPath: string, packageName: string) {
351
- const pkgFile = path.join(projectPath, 'node_modules', packageName, 'package.json');
352
- if (!fse.existsSync(pkgFile)) return null;
353
- const pkgContent = await loadJSONFile(pkgFile);
354
- return pkgContent.version;
263
+ const content = await fse.readFile(filePath, 'utf8');
264
+ return extractRestDependencies(content);
355
265
  }
@@ -0,0 +1,78 @@
1
+ import { isBuiltin } from 'node:module';
2
+ import path from 'node:path';
3
+ import ts from 'typescript';
4
+
5
+ export function extractRestDependencies(content: string): string[] {
6
+ const source = ts.createSourceFile('index.d.mts', content, ts.ScriptTarget.Latest);
7
+ // createSourceFile exposes syntax diagnostics at runtime, but not in its public return type.
8
+ const { parseDiagnostics } = source as ts.SourceFile & {
9
+ parseDiagnostics: readonly ts.Diagnostic[];
10
+ };
11
+ if (parseDiagnostics.length) {
12
+ const diagnostic = parseDiagnostics[0];
13
+ const { line, character } = source.getLineAndCharacterOfPosition(diagnostic.start ?? 0);
14
+ throw new Error(
15
+ `Invalid REST declaration at ${source.fileName}:${line + 1}:${character + 1}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`,
16
+ );
17
+ }
18
+ for (const kind of ['path', 'types'] as const) {
19
+ const references = kind === 'path' ? source.referencedFiles : source.typeReferenceDirectives;
20
+ if (references.length) {
21
+ throw new Error(
22
+ `Unsupported REST declaration reference directive: ${kind} ${JSON.stringify(references[0].fileName)}. ` +
23
+ 'The current REST bundling workflow does not support this directive.',
24
+ );
25
+ }
26
+ }
27
+ // lib references are compiler-owned, not package dependencies.
28
+ const dependencies = new Set<string>();
29
+
30
+ function addDependency(specifier: ts.Node | undefined) {
31
+ if (!specifier) return;
32
+ if (!ts.isStringLiteral(specifier)) {
33
+ throw new Error('Unsupported REST declaration module specifier');
34
+ }
35
+ const id = specifier.text;
36
+ if (
37
+ id.startsWith('.') ||
38
+ id.startsWith('#') ||
39
+ id.startsWith('\0') ||
40
+ path.isAbsolute(id) ||
41
+ path.win32.isAbsolute(id) ||
42
+ /^[a-z][a-z\d+.-]*:/i.test(id) ||
43
+ isBuiltin(id)
44
+ ) {
45
+ return;
46
+ }
47
+ if (!id || id.includes(':')) {
48
+ throw new Error(`Unsupported REST declaration package reference: ${id}`);
49
+ }
50
+ const parts = id.split('/');
51
+ if (id.startsWith('@') && (!parts[0].slice(1) || !parts[1])) {
52
+ throw new Error(`Invalid REST declaration package reference: ${id}`);
53
+ }
54
+ dependencies.add(parts.slice(0, id.startsWith('@') ? 2 : 1).join('/'));
55
+ }
56
+
57
+ function visit(node: ts.Node) {
58
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
59
+ addDependency(node.moduleSpecifier);
60
+ } else if (ts.isImportTypeNode(node)) {
61
+ if (!ts.isLiteralTypeNode(node.argument)) {
62
+ throw new Error('Unsupported REST declaration import type');
63
+ }
64
+ addDependency(node.argument.literal);
65
+ } else if (
66
+ ts.isImportEqualsDeclaration(node) &&
67
+ ts.isExternalModuleReference(node.moduleReference)
68
+ ) {
69
+ addDependency(node.moduleReference.expression);
70
+ } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
71
+ throw new Error('Unsupported REST declaration dynamic import');
72
+ }
73
+ ts.forEachChild(node, visit);
74
+ }
75
+
76
+ visit(source);
77
+ return Array.from(dependencies).sort();
78
+ }
@@ -0,0 +1,231 @@
1
+ import fse from 'fs-extra';
2
+ import path from 'node:path';
3
+ import yaml from 'yaml';
4
+
5
+ const dependencySections = ['dependencies', 'devDependencies', 'optionalDependencies'] as const;
6
+
7
+ type ImporterDependency = {
8
+ specifier?: string;
9
+ version?: string;
10
+ };
11
+
12
+ type Importer = Partial<
13
+ Record<(typeof dependencySections)[number], Record<string, ImporterDependency>>
14
+ >;
15
+
16
+ type ParsedLockfile = {
17
+ importers?: Record<string, Importer>;
18
+ };
19
+
20
+ type ModuleCandidate = {
21
+ range: string;
22
+ moduleRoot: string;
23
+ };
24
+
25
+ export async function extractRestDependencyVersions(
26
+ projectPath: string,
27
+ deps: string[],
28
+ moduleRoots: string[] = [],
29
+ ): Promise<Record<string, string>> {
30
+ const lockfilePath = path.join(projectPath, 'pnpm-lock.yaml');
31
+ const lockfileContent = await fse.readFile(lockfilePath, 'utf8');
32
+ const parsedLockfile = yaml.parse(lockfileContent) as ParsedLockfile;
33
+ const depsVersion: Record<string, string> = {};
34
+
35
+ for (const dep of deps) {
36
+ const rootRange = getPackageDependencyRangeFromLock(parsedLockfile, dep);
37
+ if (rootRange) {
38
+ depsVersion[dep] = rootRange;
39
+ continue;
40
+ }
41
+
42
+ const moduleCandidates = await getModuleCandidates(
43
+ projectPath,
44
+ parsedLockfile,
45
+ dep,
46
+ moduleRoots,
47
+ );
48
+ const distinctCandidates = getDistinctCandidates(moduleCandidates);
49
+ if (distinctCandidates.length > 1) {
50
+ throw createConflictingCandidatesError(dep, distinctCandidates);
51
+ }
52
+ if (distinctCandidates.length === 1) {
53
+ depsVersion[dep] = distinctCandidates[0].range;
54
+ continue;
55
+ }
56
+
57
+ const rootVersion = await getPackageVersionFromNodeModules(projectPath, dep);
58
+ if (rootVersion) {
59
+ depsVersion[dep] = `^${rootVersion}`;
60
+ continue;
61
+ }
62
+
63
+ throw createUnresolvedDependencyError(projectPath, dep, moduleRoots);
64
+ }
65
+
66
+ return depsVersion;
67
+ }
68
+
69
+ function getPackageDependencyRangeFromLock(
70
+ parsedLockfile: ParsedLockfile,
71
+ packageName: string,
72
+ ): string | null {
73
+ const importer = parsedLockfile.importers?.['.'];
74
+ return getImporterDependencyRange(importer, packageName);
75
+ }
76
+
77
+ function getImporterDependencyRange(
78
+ importer: Importer | undefined,
79
+ packageName: string,
80
+ ): string | null {
81
+ if (!importer) return null;
82
+
83
+ for (const section of dependencySections) {
84
+ const dependencyRange = normalizeImporterDependency(importer[section]?.[packageName]);
85
+ if (dependencyRange) return dependencyRange;
86
+ }
87
+ return null;
88
+ }
89
+
90
+ function normalizeImporterDependency(
91
+ importerDependency: ImporterDependency | undefined,
92
+ ): string | null {
93
+ if (!importerDependency) return null;
94
+
95
+ const specifier = importerDependency.specifier;
96
+ if (specifier?.startsWith('npm:')) return specifier;
97
+
98
+ const version = normalizeLockfileVersion(importerDependency.version);
99
+ if (!version) return null;
100
+ return `^${version}`;
101
+ }
102
+
103
+ function normalizeLockfileVersion(version: string | undefined): string | null {
104
+ if (!version) return null;
105
+ if (version.startsWith('link:') || version.startsWith('file:')) return null;
106
+
107
+ const versionWithoutPeers = version.split('(')[0];
108
+ if (!versionWithoutPeers) return null;
109
+ if (/^\d/.test(versionWithoutPeers)) return versionWithoutPeers;
110
+
111
+ const aliasSeparator = versionWithoutPeers.lastIndexOf('@');
112
+ if (aliasSeparator === -1) return null;
113
+
114
+ const aliasedVersion = versionWithoutPeers.slice(aliasSeparator + 1);
115
+ if (!aliasedVersion || !/^\d/.test(aliasedVersion)) return null;
116
+ return aliasedVersion;
117
+ }
118
+
119
+ async function getModuleCandidates(
120
+ projectPath: string,
121
+ parsedLockfile: ParsedLockfile,
122
+ packageName: string,
123
+ moduleRoots: string[],
124
+ ): Promise<ModuleCandidate[]> {
125
+ const candidates: ModuleCandidate[] = [];
126
+ for (const moduleRoot of moduleRoots) {
127
+ const absoluteModuleRoot = path.resolve(projectPath, moduleRoot);
128
+ if (absoluteModuleRoot === path.resolve(projectPath)) continue;
129
+
130
+ const importerKey = getImporterKey(projectPath, absoluteModuleRoot);
131
+ const importerRange = getImporterDependencyRange(
132
+ parsedLockfile.importers?.[importerKey],
133
+ packageName,
134
+ );
135
+ if (importerRange) {
136
+ candidates.push({ range: importerRange, moduleRoot: importerKey });
137
+ continue;
138
+ }
139
+
140
+ const manifestSpecifier = await getManifestDependencySpecifier(absoluteModuleRoot, packageName);
141
+ if (!manifestSpecifier) continue;
142
+
143
+ const installedVersion = await getPackageVersionFromNodeModules(
144
+ absoluteModuleRoot,
145
+ packageName,
146
+ );
147
+ if (!installedVersion) continue;
148
+ candidates.push({
149
+ range: manifestSpecifier.startsWith('npm:') ? manifestSpecifier : `^${installedVersion}`,
150
+ moduleRoot: importerKey,
151
+ });
152
+ }
153
+ return candidates;
154
+ }
155
+
156
+ async function getManifestDependencySpecifier(
157
+ moduleRoot: string,
158
+ packageName: string,
159
+ ): Promise<string | null> {
160
+ const manifestPath = path.join(moduleRoot, 'package.json');
161
+ if (!fse.existsSync(manifestPath)) return null;
162
+
163
+ const manifest = (await fse.readJson(manifestPath)) as Record<string, unknown>;
164
+ for (const section of dependencySections) {
165
+ const sectionDependencies = manifest[section];
166
+ if (!sectionDependencies || typeof sectionDependencies !== 'object') continue;
167
+ const specifier = (sectionDependencies as Record<string, unknown>)[packageName];
168
+ if (typeof specifier === 'string') return specifier;
169
+ }
170
+ return null;
171
+ }
172
+
173
+ function getDistinctCandidates(candidates: ModuleCandidate[]): ModuleCandidate[] {
174
+ const distinctCandidates = new Map<string, ModuleCandidate>();
175
+ for (const candidate of candidates) {
176
+ if (!distinctCandidates.has(candidate.range)) {
177
+ distinctCandidates.set(candidate.range, candidate);
178
+ }
179
+ }
180
+ return Array.from(distinctCandidates.values());
181
+ }
182
+
183
+ async function getPackageVersionFromNodeModules(
184
+ packageRoot: string,
185
+ packageName: string,
186
+ ): Promise<string | null> {
187
+ const pkgFile = path.join(packageRoot, 'node_modules', packageName, 'package.json');
188
+ if (!fse.existsSync(pkgFile)) return null;
189
+ const pkgContent = (await fse.readJson(pkgFile)) as Record<string, unknown>;
190
+ return typeof pkgContent.version === 'string' && pkgContent.version ? pkgContent.version : null;
191
+ }
192
+
193
+ function getImporterKey(projectPath: string, moduleRoot: string): string {
194
+ const relativePath = path.relative(projectPath, moduleRoot);
195
+ return relativePath.replaceAll(path.sep, '/') || '.';
196
+ }
197
+
198
+ function getRepoRelativePath(projectPath: string, filePath: string): string {
199
+ const relativePath = path.relative(projectPath, filePath).replaceAll(path.sep, '/');
200
+ return relativePath || '.';
201
+ }
202
+
203
+ function createConflictingCandidatesError(
204
+ packageName: string,
205
+ candidates: ModuleCandidate[],
206
+ ): Error {
207
+ const details = candidates
208
+ .map(candidate => `${candidate.moduleRoot} (${candidate.range})`)
209
+ .join(', ');
210
+ return new Error(
211
+ `Conflicting REST dependency versions for ${packageName} in module importers: ${details}. ` +
212
+ `Align the dependency versions or declare ${packageName} in the project root package.json ` +
213
+ '(pnpm-lock.yaml).',
214
+ );
215
+ }
216
+
217
+ function createUnresolvedDependencyError(
218
+ projectPath: string,
219
+ packageName: string,
220
+ moduleRoots: string[],
221
+ ): Error {
222
+ const checkedModuleRoots = moduleRoots.length
223
+ ? moduleRoots
224
+ .map(moduleRoot => getRepoRelativePath(projectPath, path.resolve(projectPath, moduleRoot)))
225
+ .join(', ')
226
+ : '(none)';
227
+ return new Error(
228
+ `Unable to resolve REST dependency version for ${packageName}. Add it to the project or an owning ` +
229
+ `module and install it; checked module roots: ${checkedModuleRoots}; lockfile: pnpm-lock.yaml.`,
230
+ );
231
+ }