@webpieces/nx-webpieces-rules 0.4.1010 → 0.4.1011

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
@@ -6,6 +6,38 @@ without any manual `project.json` wiring.
6
6
 
7
7
  Install `@webpieces/webpieces-tooling` for the complete toolchain. This package implements the Nx plugin and executors; it does not aggregate hook or PR workflow packages.
8
8
 
9
+ ## Direct dependency ownership
10
+
11
+ After installing a release containing these policies, explicitly configure `dependency-catalog`,
12
+ `root-runtime-freeze` and `dependency-ownership` in the Nx policy pack. They are independent choices;
13
+ new policy entries are required even when deliberately OFF. Setup seeds OFF entries for review,
14
+ never silently enables enforcement. Do not enable unreleased keys in the source-change PR.
15
+
16
+ `dependency-catalog` requires `catalog:` (or a named catalogue) for external entries in all four
17
+ manifest dependency sections and verifies exact semver values centrally. Internal packages use
18
+ `workspace:*`. Only pnpm-managed source manifests are governed; third-party dependency ranges,
19
+ duplicate versions and peer contexts remain the package manager's responsibility.
20
+
21
+ `root-runtime-freeze.allowedNames` is the committed name baseline for root dependencies, optional
22
+ dependencies and peers. Remove a name from that baseline when its removal should be permanent.
23
+ Root devDependencies are permitted and still catalogue-governed.
24
+
25
+ `dependency-ownership` requires production imports in the importing owner's production declarations.
26
+ Erased types and tests can use devDependencies; public declaration dependencies must be available to
27
+ consumers. Project `build.options.polyfills` and `styles` package paths are runtime inputs too.
28
+ `rootToolPaths`, `testPaths` and `artifactProbePaths` are explicit file classifications, not blanket
29
+ root-hoisting exemptions. `toolProviders` entries use `imported-name=declared-umbrella-name` only for
30
+ root tools that consume an installation bundle. Source imports, reexports, package subpaths,
31
+ literal dynamic imports/requires and source-anchored createRequire aliases are checked. Dynamic
32
+ expressions and artifact-anchored require calls fail with structured diagnostics until explicitly
33
+ reviewed in `dynamicImports`. Each entry is `file::normalized expression::package1,package2`;
34
+ whitespace in the expression is normalized. An empty package list means that exact expression
35
+ was verified local/artifact-only, never a blanket dynamic-import exemption. Named packages still
36
+ require the importing owner's appropriate declaration. Review exact probe paths when adopting.
37
+
38
+ These policies share one native build scan and run through the declared build policy contribution.
39
+ The catalogue, policy files, source, aliases and manifests invalidate the dependency validation cache.
40
+
9
41
  Add it to `nx.json`:
10
42
 
11
43
  ```jsonc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/nx-webpieces-rules",
3
- "version": "0.4.1010",
3
+ "version": "0.4.1011",
4
4
  "description": "Nx-specific webpieces validation rules, graph tooling, executors, and inference plugin.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -20,12 +20,14 @@
20
20
  "README.md"
21
21
  ],
22
22
  "dependencies": {
23
- "@webpieces/api-doc-model": "0.4.1010",
24
- "@webpieces/core-util": "0.4.1010",
25
- "@webpieces/eslint-rules": "0.4.1010",
26
- "@webpieces/rules-config": "0.4.1010",
23
+ "@webpieces/api-doc-model": "0.4.1011",
24
+ "@webpieces/core-util": "0.4.1011",
25
+ "@webpieces/eslint-rules": "0.4.1011",
26
+ "@webpieces/rules-config": "0.4.1011",
27
27
  "madge": "8.0.0",
28
- "@webpieces/rules-sdk": "0.4.1010"
28
+ "yaml": "2.8.2",
29
+ "minimatch": "10.0.1",
30
+ "@webpieces/rules-sdk": "0.4.1011"
29
31
  },
30
32
  "peerDependencies": {
31
33
  "@nx/devkit": ">=18.0.0"
@@ -41,7 +43,7 @@
41
43
  "access": "public"
42
44
  },
43
45
  "devDependencies": {
44
- "@webpieces/tooling-testkit": "0.4.1010"
46
+ "@webpieces/tooling-testkit": "0.4.1011"
45
47
  },
46
48
  "types": "./src/index.d.ts",
47
49
  "bin": {
@@ -0,0 +1,20 @@
1
+ import { BaseRuleConfig, SchemaShape } from '@webpieces/rules-sdk';
2
+ import { StructuralMode } from './rule-configs';
3
+ export declare class DependencyCatalogConfig extends BaseRuleConfig {
4
+ mode?: StructuralMode;
5
+ static readonly SCHEMA: SchemaShape<DependencyCatalogConfig>;
6
+ }
7
+ export declare class RootRuntimeFreezeConfig extends BaseRuleConfig {
8
+ mode?: StructuralMode;
9
+ allowedNames?: string[];
10
+ static readonly SCHEMA: SchemaShape<RootRuntimeFreezeConfig>;
11
+ }
12
+ export declare class DependencyOwnershipConfig extends BaseRuleConfig {
13
+ mode?: StructuralMode;
14
+ rootToolPaths?: string[];
15
+ testPaths?: string[];
16
+ artifactProbePaths?: string[];
17
+ toolProviders?: string[];
18
+ dynamicImports?: string[];
19
+ static readonly SCHEMA: SchemaShape<DependencyOwnershipConfig>;
20
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DependencyOwnershipConfig = exports.RootRuntimeFreezeConfig = exports.DependencyCatalogConfig = void 0;
4
+ const rules_sdk_1 = require("@webpieces/rules-sdk");
5
+ const rule_configs_1 = require("./rule-configs");
6
+ class DependencyCatalogConfig extends rules_sdk_1.BaseRuleConfig {
7
+ static SCHEMA = {
8
+ mode: new rules_sdk_1.FieldDef('string', rule_configs_1.STRUCTURAL_MODES),
9
+ };
10
+ }
11
+ exports.DependencyCatalogConfig = DependencyCatalogConfig;
12
+ class RootRuntimeFreezeConfig extends rules_sdk_1.BaseRuleConfig {
13
+ allowedNames;
14
+ static SCHEMA = {
15
+ mode: new rules_sdk_1.FieldDef('string', rule_configs_1.STRUCTURAL_MODES),
16
+ allowedNames: new rules_sdk_1.FieldDef('string[]'),
17
+ };
18
+ }
19
+ exports.RootRuntimeFreezeConfig = RootRuntimeFreezeConfig;
20
+ class DependencyOwnershipConfig extends rules_sdk_1.BaseRuleConfig {
21
+ rootToolPaths;
22
+ testPaths;
23
+ artifactProbePaths;
24
+ toolProviders;
25
+ dynamicImports;
26
+ static SCHEMA = {
27
+ mode: new rules_sdk_1.FieldDef('string', rule_configs_1.STRUCTURAL_MODES),
28
+ rootToolPaths: new rules_sdk_1.FieldDef('string[]'),
29
+ testPaths: new rules_sdk_1.FieldDef('string[]'),
30
+ artifactProbePaths: new rules_sdk_1.FieldDef('string[]'),
31
+ toolProviders: new rules_sdk_1.FieldDef('string[]'),
32
+ dynamicImports: new rules_sdk_1.FieldDef('string[]'),
33
+ };
34
+ }
35
+ exports.DependencyOwnershipConfig = DependencyOwnershipConfig;
36
+ //# sourceMappingURL=dependency-policy-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dependency-policy-config.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/configs/dependency-policy-config.ts"],"names":[],"mappings":";;;AAAA,oDAA6E;AAC7E,iDAAkE;AAElE,MAAa,uBAAwB,SAAQ,0BAAc;IAEvD,MAAM,CAAU,MAAM,GAAyC;QAC3D,IAAI,EAAE,IAAI,oBAAQ,CAAC,QAAQ,EAAE,+BAAgB,CAAC;KACjD,CAAC;;AAJN,0DAKC;AAED,MAAa,uBAAwB,SAAQ,0BAAc;IAEvD,YAAY,CAAY;IACxB,MAAM,CAAU,MAAM,GAAyC;QAC3D,IAAI,EAAE,IAAI,oBAAQ,CAAC,QAAQ,EAAE,+BAAgB,CAAC;QAC9C,YAAY,EAAE,IAAI,oBAAQ,CAAC,UAAU,CAAC;KACzC,CAAC;;AANN,0DAOC;AAED,MAAa,yBAA0B,SAAQ,0BAAc;IAEzD,aAAa,CAAY;IACzB,SAAS,CAAY;IACrB,kBAAkB,CAAY;IAC9B,aAAa,CAAY;IACzB,cAAc,CAAY;IAC1B,MAAM,CAAU,MAAM,GAA2C;QAC7D,IAAI,EAAE,IAAI,oBAAQ,CAAC,QAAQ,EAAE,+BAAgB,CAAC;QAC9C,aAAa,EAAE,IAAI,oBAAQ,CAAC,UAAU,CAAC;QACvC,SAAS,EAAE,IAAI,oBAAQ,CAAC,UAAU,CAAC;QACnC,kBAAkB,EAAE,IAAI,oBAAQ,CAAC,UAAU,CAAC;QAC5C,aAAa,EAAE,IAAI,oBAAQ,CAAC,UAAU,CAAC;QACvC,cAAc,EAAE,IAAI,oBAAQ,CAAC,UAAU,CAAC;KAC3C,CAAC;;AAdN,8DAeC","sourcesContent":["import { BaseRuleConfig, FieldDef, SchemaShape } from '@webpieces/rules-sdk';\nimport { STRUCTURAL_MODES, StructuralMode } from './rule-configs';\n\nexport class DependencyCatalogConfig extends BaseRuleConfig {\n declare mode?: StructuralMode;\n static readonly SCHEMA: SchemaShape<DependencyCatalogConfig> = {\n mode: new FieldDef('string', STRUCTURAL_MODES),\n };\n}\n\nexport class RootRuntimeFreezeConfig extends BaseRuleConfig {\n declare mode?: StructuralMode;\n allowedNames?: string[];\n static readonly SCHEMA: SchemaShape<RootRuntimeFreezeConfig> = {\n mode: new FieldDef('string', STRUCTURAL_MODES),\n allowedNames: new FieldDef('string[]'),\n };\n}\n\nexport class DependencyOwnershipConfig extends BaseRuleConfig {\n declare mode?: StructuralMode;\n rootToolPaths?: string[];\n testPaths?: string[];\n artifactProbePaths?: string[];\n toolProviders?: string[];\n dynamicImports?: string[];\n static readonly SCHEMA: SchemaShape<DependencyOwnershipConfig> = {\n mode: new FieldDef('string', STRUCTURAL_MODES),\n rootToolPaths: new FieldDef('string[]'),\n testPaths: new FieldDef('string[]'),\n artifactProbePaths: new FieldDef('string[]'),\n toolProviders: new FieldDef('string[]'),\n dynamicImports: new FieldDef('string[]'),\n };\n}\n"]}
@@ -20,4 +20,5 @@ export interface ExecutorResult {
20
20
  success: boolean;
21
21
  }
22
22
  export declare function findPackageJsonFiles(dir: string, basePath?: string): string[];
23
- export default function runExecutor(_options: ValidateVersionsLockedOptions, context: ExecutorContext): Promise<ExecutorResult>;
23
+ declare const _default: (_options: ValidateVersionsLockedOptions, context: ExecutorContext) => Promise<ExecutorResult>;
24
+ export default _default;
@@ -16,12 +16,13 @@
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.findPackageJsonFiles = findPackageJsonFiles;
19
- exports.default = runExecutor;
20
19
  const tslib_1 = require("tslib");
21
20
  const fs = tslib_1.__importStar(require("fs"));
22
21
  const path = tslib_1.__importStar(require("path"));
23
22
  const rule_gate_1 = require("../../lib/rule-gate");
24
- const toError_1 = require("../../toError");
23
+ const dependency_workspace_1 = require("../../lib/dependency-workspace");
24
+ const dependency_policies_1 = require("../../lib/dependency-policies");
25
+ const rules_config_1 = require("@webpieces/rules-config");
25
26
  // webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file
26
27
  // Find all package.json files except node_modules, dist, .nx, .angular
27
28
  function findPackageJsonFiles(dir, basePath = '') {
@@ -59,265 +60,53 @@ function findPackageJsonFiles(dir, basePath = '') {
59
60
  }
60
61
  return files;
61
62
  }
62
- // Check if a version string uses semver ranges
63
- function hasSemverRange(version) {
64
- // Allow workspace protocol
65
- if (version.startsWith('workspace:')) {
66
- return false;
67
- }
68
- // Allow file: protocol (for local packages)
69
- if (version.startsWith('file:')) {
70
- return false;
71
- }
72
- // Check for common semver range patterns
73
- const semverPatterns = [
74
- /^\^/, // ^1.2.3
75
- /^~/, // ~1.2.3
76
- /^\+/, // +1.2.3
77
- /^\*/, // *
78
- /^>/, // >1.2.3
79
- /^</, // <1.2.3
80
- /^>=/, // >=1.2.3
81
- /^<=/, // <=1.2.3
82
- /\|\|/, // 1.2.3 || 2.x
83
- / - /, // 1.2.3 - 2.3.4
84
- /^\d+\.x/, // 1.x, 1.2.x
85
- /^latest$/, // latest
86
- /^next$/, // next
87
- ];
88
- return semverPatterns.some((pattern) => pattern.test(version));
89
- }
90
- // webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file
91
- // Validate a single package.json file for semver ranges
92
- function validatePackageJson(filePath) {
93
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
94
- try {
95
- const content = fs.readFileSync(filePath, 'utf-8');
96
- const pkg = JSON.parse(content);
63
+ /** Resolve catalogue pins before comparing authored direct versions. Published peers remain ranges. */
64
+ class VersionsLockedExecutor {
65
+ async run(_options, context) {
66
+ if (new rule_gate_1.RuleGate().isDisabled(context.root, 'validate-versions-locked', true))
67
+ return { success: true };
68
+ const workspace = new dependency_workspace_1.DependencyWorkspace(context.root);
69
+ const owners = [new dependency_workspace_1.DependencyOwner('.', workspace.rootManifest), ...workspace.owners];
70
+ const versions = new Map();
97
71
  const errors = [];
98
- // Check dependencies
99
- if (pkg.dependencies) {
100
- for (const [name, version] of Object.entries(pkg.dependencies)) {
101
- // Skip internal workspace packages
102
- if (name.startsWith('@webpieces/')) {
103
- continue;
104
- }
105
- if (hasSemverRange(version)) {
106
- errors.push(`dependencies.${name}: "${version}" uses semver range (must be locked to exact version)`);
107
- }
108
- }
109
- }
110
- // Check devDependencies
111
- if (pkg.devDependencies) {
112
- for (const [name, version] of Object.entries(pkg.devDependencies)) {
113
- // Skip internal workspace packages
114
- if (name.startsWith('@webpieces/')) {
115
- continue;
116
- }
117
- if (hasSemverRange(version)) {
118
- errors.push(`devDependencies.${name}: "${version}" uses semver range (must be locked to exact version)`);
119
- }
120
- }
121
- }
122
- // Check peerDependencies (these can have ranges for compatibility)
123
- // We don't validate peerDependencies for semver ranges since they're meant to be flexible
124
- return errors;
125
- }
126
- catch (err) {
127
- const error = (0, toError_1.toError)(err);
128
- return [`Failed to parse ${filePath}: ${error.message}`];
129
- }
130
- }
131
- // webpieces-disable max-lines-new-methods -- Collecting dependencies from all package.json files
132
- // Collect all dependency versions from all package.json files
133
- function collectAllDependencies(workspaceRoot) {
134
- const dependencyMap = new Map();
135
- const packageFiles = findPackageJsonFiles(workspaceRoot);
136
- for (const filePath of packageFiles) {
137
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
138
- try {
139
- const content = fs.readFileSync(filePath, 'utf-8');
140
- const pkg = JSON.parse(content);
141
- const relativePath = path.relative(workspaceRoot, filePath);
142
- // Collect dependencies
143
- if (pkg.dependencies) {
144
- for (const [name, version] of Object.entries(pkg.dependencies)) {
145
- // Skip internal workspace packages
146
- if (name.startsWith('@webpieces/'))
72
+ for (const owner of owners) {
73
+ if (!owner.manifest)
74
+ continue;
75
+ for (const section of [
76
+ 'dependencies',
77
+ 'devDependencies',
78
+ 'optionalDependencies',
79
+ ]) {
80
+ for (const declaration of Object.entries(owner.manifest[section] ?? {})) {
81
+ const name = declaration[0];
82
+ const specifier = declaration[1];
83
+ if (specifier.startsWith('workspace:') || specifier.startsWith('file:'))
147
84
  continue;
148
- const usage = {
149
- version: version,
150
- file: relativePath,
151
- type: 'dependencies'
152
- };
153
- if (!dependencyMap.has(name)) {
154
- dependencyMap.set(name, []);
155
- }
156
- dependencyMap.get(name).push(usage);
157
- }
158
- }
159
- // Collect devDependencies
160
- if (pkg.devDependencies) {
161
- for (const [name, version] of Object.entries(pkg.devDependencies)) {
162
- // Skip internal workspace packages
163
- if (name.startsWith('@webpieces/'))
85
+ const catalog = specifier.slice('catalog:'.length);
86
+ const pin = specifier.startsWith('catalog:')
87
+ ? (catalog
88
+ ? workspace.catalog.catalogs?.[catalog]
89
+ : workspace.catalog.catalog)?.[name]
90
+ : specifier;
91
+ const where = `${owner.directory}/package.json ${section}.${name}`;
92
+ if (!pin || !new dependency_policies_1.DependencyVersion().isExact(pin)) {
93
+ errors.push(`${where}: ${specifier} must resolve to an exact locked version, found ${String(pin)}`);
164
94
  continue;
165
- const usage = {
166
- version: version,
167
- file: relativePath,
168
- type: 'devDependencies'
169
- };
170
- if (!dependencyMap.has(name)) {
171
- dependencyMap.set(name, []);
172
95
  }
173
- dependencyMap.get(name).push(usage);
96
+ const previous = versions.get(name);
97
+ if (previous && previous !== pin)
98
+ errors.push(`${where}: conflicting direct version ${pin}, already declared ${previous}`);
99
+ versions.set(name, pin);
174
100
  }
175
101
  }
176
102
  }
177
- catch (err) {
178
- // const error = toError(err);
179
- // Intentionally skip files that can't be parsed - this is expected for some package.json files
180
- }
181
- }
182
- return dependencyMap;
183
- }
184
- // webpieces-disable max-lines-new-methods -- Simple iteration logic, splitting would reduce clarity
185
- // Check for version conflicts across package.json files
186
- function checkVersionConflicts(workspaceRoot) {
187
- console.log('\n🔍 Checking for version conflicts across package.json files:');
188
- const dependencyMap = collectAllDependencies(workspaceRoot);
189
- const conflicts = [];
190
- for (const [packageName, usages] of dependencyMap.entries()) {
191
- // Get unique versions (ignoring workspace: and file: protocols)
192
- const versions = new Set(usages
193
- .map(u => u.version)
194
- .filter(v => !v.startsWith('workspace:') && !v.startsWith('file:')));
195
- if (versions.size > 1) {
196
- const conflictDetails = usages
197
- .filter(u => !u.version.startsWith('workspace:') && !u.version.startsWith('file:'))
198
- .map(u => ` ${u.file} (${u.type}): ${u.version}`)
199
- .join('\n');
200
- conflicts.push(` ❌ ${packageName} has ${versions.size} different versions:\n${conflictDetails}`);
201
- }
202
- }
203
- if (conflicts.length === 0) {
204
- console.log(' ✅ No version conflicts found');
205
- }
206
- else {
207
- for (const conflict of conflicts) {
208
- console.log(conflict);
209
- }
210
- }
211
- return conflicts;
212
- }
213
- /**
214
- * Prints the educational message explaining why semver ranges are forbidden.
215
- * This helps developers understand the rationale behind locked versions.
216
- */
217
- // webpieces-disable max-lines-new-methods -- Educational message template, splitting reduces clarity
218
- function printSemverRangeEducationalMessage(semverErrors) {
219
- console.log(`
220
- ❌ SEMVER RANGES DETECTED - BUILD FAILED
221
-
222
- Found ${semverErrors} package(s) using semver ranges (^, ~, *, etc.) instead of locked versions.
223
-
224
- WHY THIS IS A HARD FAILURE:
225
- ═══════════════════════════════════════════════════════════════════════════════
226
-
227
- 1. MICRO BUGS ARE REAL
228
- Thinking that patch versions (1.4.5 → 1.4.6) don't introduce bugs is wrong.
229
- They do. Sometimes what looks like an "easy fix" breaks things in subtle ways.
230
-
231
- 2. GIT BISECT BECOMES USELESS
232
- When you run "git bisect" to find when a bug was introduced, it fails if
233
- software changed OUTSIDE of git. You checkout an old commit, but node_modules
234
- has different versions than when that commit was made. The bug persists even
235
- in "known good" commits because the library versions drifted.
236
-
237
- 3. THE "MAGIC BUG" PROBLEM
238
- You checkout code from 6 months ago to debug an issue. The bug is still there!
239
- But it wasn't there 6 months ago... The culprit: a minor version upgrade that
240
- happened silently without any PR or git commit. Impossible to track down.
241
-
242
- 4. CHANGES OUTSIDE GIT = BAD
243
- Every change to your software should be tracked in version control.
244
- Implicit library upgrades via semver ranges violate this principle.
245
-
246
- THE SOLUTION:
247
- ═══════════════════════════════════════════════════════════════════════════════
248
-
249
- Use LOCKED (exact) versions for all dependencies:
250
- ❌ "lodash": "^4.17.21" <- BAD: allows 4.17.22, 4.18.0, etc.
251
- ❌ "lodash": "~4.17.21" <- BAD: allows 4.17.22, 4.17.23, etc.
252
- ✅ "lodash": "4.17.21" <- GOOD: locked to this exact version
253
-
254
- To upgrade libraries, use an explicit process:
255
- 1. Run: npm update <package-name>
256
- 2. Test thoroughly
257
- 3. Commit the package.json AND package-lock.json changes
258
- 4. Create a PR so the upgrade is reviewed and tracked in git history
259
-
260
- This way, every library change is:
261
- • Intentional (not accidental)
262
- • Reviewed (via PR)
263
- • Tracked (in git history)
264
- • Bisectable (git bisect works correctly)
265
-
266
- `);
267
- }
268
- // Check semver ranges in all package.json files - FAILS if any found
269
- function checkSemverRanges(workspaceRoot) {
270
- console.log('\n📋 Checking for unlocked versions (semver ranges):');
271
- const packageFiles = findPackageJsonFiles(workspaceRoot);
272
- let semverErrors = 0;
273
- for (const filePath of packageFiles) {
274
- const relativePath = path.relative(workspaceRoot, filePath);
275
- const errors = validatePackageJson(filePath);
276
- if (errors.length > 0) {
277
- console.log(` ❌ ${relativePath}:`);
278
- for (const error of errors) {
279
- console.log(` ${error}`);
280
- }
281
- semverErrors += errors.length;
282
- }
283
- else {
284
- console.log(` ✅ ${relativePath}`);
285
- }
286
- }
287
- return { errors: semverErrors };
288
- }
289
- async function runExecutor(_options, context) {
290
- const workspaceRoot = context.root;
291
- // Time-boxable (honorEpoch = true): a schedule is not a baseline — "do not enforce until <epoch>
292
- // / off <branch>" is coherent even with nothing to grandfather. See rule-configs.ts (five-validator block).
293
- if (new rule_gate_1.RuleGate().isDisabled(workspaceRoot, 'validate-versions-locked', true)) {
103
+ if (errors.length)
104
+ throw new rules_config_1.RuleFailError('validate-versions-locked', errors.join('\n'), undefined, undefined, [
105
+ new rules_config_1.Option('Use exact consistent direct versions or exact catalogue pins; preserve workspace:* for internal owners', true),
106
+ ]);
294
107
  return { success: true };
295
108
  }
296
- console.log('\n🔒 Validating Package Versions are LOCKED and CONSISTENT\n');
297
- // Step 1: Check for semver ranges (FAILS if any found)
298
- const semverResult = checkSemverRanges(workspaceRoot);
299
- const semverErrors = semverResult.errors;
300
- const packageFiles = findPackageJsonFiles(workspaceRoot);
301
- // Step 2: Check for version conflicts across package.json files
302
- const versionConflicts = checkVersionConflicts(workspaceRoot);
303
- // Summary
304
- console.log(`\n📊 Summary:`);
305
- console.log(` Files checked: ${packageFiles.length}`);
306
- console.log(` Unlocked versions (semver ranges): ${semverErrors}`);
307
- console.log(` Version conflicts: ${versionConflicts.length}`);
308
- // Fail on semver ranges with educational message
309
- if (semverErrors > 0) {
310
- printSemverRangeEducationalMessage(semverErrors);
311
- return { success: false };
312
- }
313
- // Fail on version conflicts
314
- if (versionConflicts.length > 0) {
315
- console.log('\n❌ VALIDATION FAILED!');
316
- console.log(' Fix version conflicts - all package.json files must use the same version for each dependency.');
317
- console.log(' This prevents "works on my machine" bugs where different projects use different library versions.\n');
318
- return { success: false };
319
- }
320
- console.log('\n✅ VALIDATION PASSED! All versions are locked and consistent.');
321
- return { success: true };
322
109
  }
110
+ const executor = new VersionsLockedExecutor();
111
+ exports.default = executor.run.bind(executor);
323
112
  //# sourceMappingURL=executor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-versions-locked/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAkBH,oDA2CC;AA8QD,8BA4CC;;AApXD,+CAAyB;AACzB,mDAA6B;AAC7B,mDAA+C;AAC/C,2CAAwC;AAUxC,iGAAiG;AACjG,uEAAuE;AACvE,SAAgB,oBAAoB,CAAC,GAAW,EAAE,QAAQ,GAAG,EAAE;IAC3D,M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AE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,4BAA4B;IAC5B,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC9B,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,kGAAkG,CAAC,CAAC;QAChH,OAAO,CAAC,GAAG,CAAC,wGAAwG,CAAC,CAAC;QACtH,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,gEAAgE,CAAC,CAAC;IAC9E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC7B,CAAC","sourcesContent":["/**\n * Validate Versions Locked Executor\n *\n * Validates that package.json versions are:\n * 1. LOCKED (exact versions, no semver ranges like ^, ~, *)\n * 2. CONSISTENT across all package.json files (no version conflicts)\n *\n * Why locked versions matter:\n * - Micro bugs ARE introduced via patch versions (1.4.5 → 1.4.6)\n * - git bisect fails when software changes OUTSIDE of git\n * - Library upgrades must be explicit via PR/commit, not implicit drift\n *\n * Usage:\n * nx run architecture:validate-versions-locked\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { RuleGate } from '../../lib/rule-gate';\nimport { toError } from '../../toError';\n\nexport interface ValidateVersionsLockedOptions {\n // No options needed\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file\n// Find all package.json files except node_modules, dist, .nx, .angular\nexport function findPackageJsonFiles(dir: string, basePath = ''): string[] {\n const files: string[] = [];\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const relativePath = path.join(basePath, item);\n\n // Skip these directories\n if (\n ['node_modules', 'dist', '.nx', '.angular', 'tmp', '.git'].includes(\n item,\n )\n ) {\n continue;\n }\n\n // Skip platform-specific node_modules backups (node_modules_mac, node_modules_linux, etc.)\n if (item.startsWith('node_modules_')) {\n continue;\n }\n\n // Skip all hidden directories (starting with .)\n if (item.startsWith('.')) {\n continue;\n }\n\n const stat = fs.statSync(fullPath);\n if (stat.isDirectory()) {\n // Don't descend into a nested git repository (e.g. a clone under repositories/): it is a\n // separate project with its own version policy, NOT part of this monorepo's version lock.\n // The presence of a `.git` entry (dir for a real clone, file for a worktree/submodule)\n // marks a repo boundary — the same signal the AI guards use to scope to the current repo.\n if (fs.existsSync(path.join(fullPath, '.git'))) {\n continue;\n }\n files.push(...findPackageJsonFiles(fullPath, relativePath));\n } else if (item === 'package.json') {\n files.push(fullPath);\n }\n }\n\n return files;\n}\n\n// Check if a version string uses semver ranges\nfunction hasSemverRange(version: string): boolean {\n // Allow workspace protocol\n if (version.startsWith('workspace:')) {\n return false;\n }\n\n // Allow file: protocol (for local packages)\n if (version.startsWith('file:')) {\n return false;\n }\n\n // Check for common semver range patterns\n const semverPatterns = [\n /^\\^/, // ^1.2.3\n /^~/, // ~1.2.3\n /^\\+/, // +1.2.3\n /^\\*/, // *\n /^>/, // >1.2.3\n /^</, // <1.2.3\n /^>=/, // >=1.2.3\n /^<=/, // <=1.2.3\n /\\|\\|/, // 1.2.3 || 2.x\n / - /, // 1.2.3 - 2.3.4\n /^\\d+\\.x/, // 1.x, 1.2.x\n /^latest$/, // latest\n /^next$/, // next\n ];\n\n return semverPatterns.some((pattern) => pattern.test(version));\n}\n\n// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file\n// Validate a single package.json file for semver ranges\nfunction validatePackageJson(filePath: string): string[] {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const pkg = JSON.parse(content);\n const errors: string[] = [];\n\n // Check dependencies\n if (pkg.dependencies) {\n for (const [name, version] of Object.entries(pkg.dependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) {\n continue;\n }\n\n if (hasSemverRange(version as string)) {\n errors.push(\n `dependencies.${name}: \"${version}\" uses semver range (must be locked to exact version)`,\n );\n }\n }\n }\n\n // Check devDependencies\n if (pkg.devDependencies) {\n for (const [name, version] of Object.entries(pkg.devDependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) {\n continue;\n }\n\n if (hasSemverRange(version as string)) {\n errors.push(\n `devDependencies.${name}: \"${version}\" uses semver range (must be locked to exact version)`,\n );\n }\n }\n }\n\n // Check peerDependencies (these can have ranges for compatibility)\n // We don't validate peerDependencies for semver ranges since they're meant to be flexible\n\n return errors;\n } catch (err: unknown) {\n const error = toError(err);\n return [`Failed to parse ${filePath}: ${error.message}`];\n }\n}\n\n// Track all dependency versions across the monorepo\ninterface DependencyUsage {\n version: string;\n file: string;\n type: 'dependencies' | 'devDependencies';\n}\n\n// webpieces-disable max-lines-new-methods -- Collecting dependencies from all package.json files\n// Collect all dependency versions from all package.json files\nfunction collectAllDependencies(workspaceRoot: string): Map<string, DependencyUsage[]> {\n const dependencyMap = new Map<string, DependencyUsage[]>();\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n\n for (const filePath of packageFiles) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n const pkg = JSON.parse(content);\n const relativePath = path.relative(workspaceRoot, filePath);\n\n // Collect dependencies\n if (pkg.dependencies) {\n for (const [name, version] of Object.entries(pkg.dependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) continue;\n\n const usage: DependencyUsage = {\n version: version as string,\n file: relativePath,\n type: 'dependencies'\n };\n\n if (!dependencyMap.has(name)) {\n dependencyMap.set(name, []);\n }\n dependencyMap.get(name)!.push(usage);\n }\n }\n\n // Collect devDependencies\n if (pkg.devDependencies) {\n for (const [name, version] of Object.entries(pkg.devDependencies)) {\n // Skip internal workspace packages\n if (name.startsWith('@webpieces/')) continue;\n\n const usage: DependencyUsage = {\n version: version as string,\n file: relativePath,\n type: 'devDependencies'\n };\n\n if (!dependencyMap.has(name)) {\n dependencyMap.set(name, []);\n }\n dependencyMap.get(name)!.push(usage);\n }\n }\n } catch (err: unknown) {\n // const error = toError(err);\n // Intentionally skip files that can't be parsed - this is expected for some package.json files\n }\n }\n\n return dependencyMap;\n}\n\n// webpieces-disable max-lines-new-methods -- Simple iteration logic, splitting would reduce clarity\n// Check for version conflicts across package.json files\nfunction checkVersionConflicts(workspaceRoot: string): string[] {\n console.log('\\n🔍 Checking for version conflicts across package.json files:');\n\n const dependencyMap = collectAllDependencies(workspaceRoot);\n const conflicts: string[] = [];\n\n for (const [packageName, usages] of dependencyMap.entries()) {\n // Get unique versions (ignoring workspace: and file: protocols)\n const versions = new Set(\n usages\n .map(u => u.version)\n .filter(v => !v.startsWith('workspace:') && !v.startsWith('file:'))\n );\n\n if (versions.size > 1) {\n const conflictDetails = usages\n .filter(u => !u.version.startsWith('workspace:') && !u.version.startsWith('file:'))\n .map(u => ` ${u.file} (${u.type}): ${u.version}`)\n .join('\\n');\n\n conflicts.push(` ❌ ${packageName} has ${versions.size} different versions:\\n${conflictDetails}`);\n }\n }\n\n if (conflicts.length === 0) {\n console.log(' ✅ No version conflicts found');\n } else {\n for (const conflict of conflicts) {\n console.log(conflict);\n }\n }\n\n return conflicts;\n}\n\n/**\n * Prints the educational message explaining why semver ranges are forbidden.\n * This helps developers understand the rationale behind locked versions.\n */\n// webpieces-disable max-lines-new-methods -- Educational message template, splitting reduces clarity\nfunction printSemverRangeEducationalMessage(semverErrors: number): void {\n console.log(`\n❌ SEMVER RANGES DETECTED - BUILD FAILED\n\nFound ${semverErrors} package(s) using semver ranges (^, ~, *, etc.) instead of locked versions.\n\nWHY THIS IS A HARD FAILURE:\n═══════════════════════════════════════════════════════════════════════════════\n\n1. MICRO BUGS ARE REAL\n Thinking that patch versions (1.4.5 → 1.4.6) don't introduce bugs is wrong.\n They do. Sometimes what looks like an \"easy fix\" breaks things in subtle ways.\n\n2. GIT BISECT BECOMES USELESS\n When you run \"git bisect\" to find when a bug was introduced, it fails if\n software changed OUTSIDE of git. You checkout an old commit, but node_modules\n has different versions than when that commit was made. The bug persists even\n in \"known good\" commits because the library versions drifted.\n\n3. THE \"MAGIC BUG\" PROBLEM\n You checkout code from 6 months ago to debug an issue. The bug is still there!\n But it wasn't there 6 months ago... The culprit: a minor version upgrade that\n happened silently without any PR or git commit. Impossible to track down.\n\n4. CHANGES OUTSIDE GIT = BAD\n Every change to your software should be tracked in version control.\n Implicit library upgrades via semver ranges violate this principle.\n\nTHE SOLUTION:\n═══════════════════════════════════════════════════════════════════════════════\n\nUse LOCKED (exact) versions for all dependencies:\n ❌ \"lodash\": \"^4.17.21\" <- BAD: allows 4.17.22, 4.18.0, etc.\n ❌ \"lodash\": \"~4.17.21\" <- BAD: allows 4.17.22, 4.17.23, etc.\n ✅ \"lodash\": \"4.17.21\" <- GOOD: locked to this exact version\n\nTo upgrade libraries, use an explicit process:\n 1. Run: npm update <package-name>\n 2. Test thoroughly\n 3. Commit the package.json AND package-lock.json changes\n 4. Create a PR so the upgrade is reviewed and tracked in git history\n\nThis way, every library change is:\n • Intentional (not accidental)\n • Reviewed (via PR)\n • Tracked (in git history)\n • Bisectable (git bisect works correctly)\n\n`);\n}\n\ntype SemverRangeResult = { errors: number };\n\n// Check semver ranges in all package.json files - FAILS if any found\nfunction checkSemverRanges(workspaceRoot: string): SemverRangeResult {\n console.log('\\n📋 Checking for unlocked versions (semver ranges):');\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n let semverErrors = 0;\n\n for (const filePath of packageFiles) {\n const relativePath = path.relative(workspaceRoot, filePath);\n const errors = validatePackageJson(filePath);\n\n if (errors.length > 0) {\n console.log(` ❌ ${relativePath}:`);\n for (const error of errors) {\n console.log(` ${error}`);\n }\n semverErrors += errors.length;\n } else {\n console.log(` ✅ ${relativePath}`);\n }\n }\n\n return { errors: semverErrors };\n}\n\nexport default async function runExecutor(\n _options: ValidateVersionsLockedOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n\n // Time-boxable (honorEpoch = true): a schedule is not a baseline — \"do not enforce until <epoch>\n // / off <branch>\" is coherent even with nothing to grandfather. See rule-configs.ts (five-validator block).\n if (new RuleGate().isDisabled(workspaceRoot, 'validate-versions-locked', true)) {\n return { success: true };\n }\n\n console.log('\\n🔒 Validating Package Versions are LOCKED and CONSISTENT\\n');\n\n // Step 1: Check for semver ranges (FAILS if any found)\n const semverResult = checkSemverRanges(workspaceRoot);\n const semverErrors = semverResult.errors;\n const packageFiles = findPackageJsonFiles(workspaceRoot);\n\n // Step 2: Check for version conflicts across package.json files\n const versionConflicts = checkVersionConflicts(workspaceRoot);\n\n // Summary\n console.log(`\\n📊 Summary:`);\n console.log(` Files checked: ${packageFiles.length}`);\n console.log(` Unlocked versions (semver ranges): ${semverErrors}`);\n console.log(` Version conflicts: ${versionConflicts.length}`);\n\n // Fail on semver ranges with educational message\n if (semverErrors > 0) {\n printSemverRangeEducationalMessage(semverErrors);\n return { success: false };\n }\n\n // Fail on version conflicts\n if (versionConflicts.length > 0) {\n console.log('\\n❌ VALIDATION FAILED!');\n console.log(' Fix version conflicts - all package.json files must use the same version for each dependency.');\n console.log(' This prevents \"works on my machine\" bugs where different projects use different library versions.\\n');\n return { success: false };\n }\n\n console.log('\\n✅ VALIDATION PASSED! All versions are locked and consistent.');\n return { success: true };\n}\n"]}
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-versions-locked/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAoBH,oDAuCC;;AAxDD,+CAAyB;AACzB,mDAA6B;AAC7B,mDAA+C;AAC/C,yEAAsF;AACtF,uEAAkE;AAClE,0DAAgE;AAUhE,iGAAiG;AACjG,uEAAuE;AACvE,SAAgB,oBAAoB,CAAC,GAAW,EAAE,QAAQ,GAAG,EAAE;IAC3D,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM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AAC,OAAO,CAAC;4BACvC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC;wBAC1C,CAAC,CAAC,SAAS,CAAC;oBAChB,MAAM,KAAK,GAAG,GAAG,KAAK,CAAC,SAAS,iBAAiB,OAAO,IAAI,IAAI,EAAE,CAAC;oBACnE,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,uCAAiB,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;wBAChD,MAAM,CAAC,IAAI,CACP,GAAG,KAAK,KAAK,SAAS,mDAAmD,MAAM,CAAC,GAAG,CAAC,EAAE,CACzF,CAAC;wBACF,SAAS;oBACb,CAAC;oBACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;oBACpC,IAAI,QAAQ,IAAI,QAAQ,KAAK,GAAG;wBAC5B,MAAM,CAAC,IAAI,CACP,GAAG,KAAK,gCAAgC,GAAG,sBAAsB,QAAQ,EAAE,CAC9E,CAAC;oBACN,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;gBAC5B,CAAC;YACL,CAAC;QACL,CAAC;QACD,IAAI,MAAM,CAAC,MAAM;YACb,MAAM,IAAI,4BAAa,CACnB,0BAA0B,EAC1B,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EACjB,SAAS,EACT,SAAS,EACT;gBACI,IAAI,qBAAM,CACN,wGAAwG,EACxG,IAAI,CACP;aACJ,CACJ,CAAC;QACN,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;CACJ;AAED,MAAM,QAAQ,GAAG,IAAI,sBAAsB,EAAE,CAAC;AAC9C,kBAAe,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC","sourcesContent":["/**\n * Validate Versions Locked Executor\n *\n * Validates that package.json versions are:\n * 1. LOCKED (exact versions, no semver ranges like ^, ~, *)\n * 2. CONSISTENT across all package.json files (no version conflicts)\n *\n * Why locked versions matter:\n * - Micro bugs ARE introduced via patch versions (1.4.5 → 1.4.6)\n * - git bisect fails when software changes OUTSIDE of git\n * - Library upgrades must be explicit via PR/commit, not implicit drift\n *\n * Usage:\n * nx run architecture:validate-versions-locked\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { RuleGate } from '../../lib/rule-gate';\nimport { DependencyWorkspace, DependencyOwner } from '../../lib/dependency-workspace';\nimport { DependencyVersion } from '../../lib/dependency-policies';\nimport { RuleFailError, Option } from '@webpieces/rules-config';\n\nexport interface ValidateVersionsLockedOptions {\n // No options needed\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n// webpieces-disable max-lines-new-methods -- Existing method from renamed validate-versions file\n// Find all package.json files except node_modules, dist, .nx, .angular\nexport function findPackageJsonFiles(dir: string, basePath = ''): string[] {\n const files: string[] = [];\n const items = fs.readdirSync(dir);\n\n for (const item of items) {\n const fullPath = path.join(dir, item);\n const relativePath = path.join(basePath, item);\n\n // Skip these directories\n if (['node_modules', 'dist', '.nx', '.angular', 'tmp', '.git'].includes(item)) {\n continue;\n }\n\n // Skip platform-specific node_modules backups (node_modules_mac, node_modules_linux, etc.)\n if (item.startsWith('node_modules_')) {\n continue;\n }\n\n // Skip all hidden directories (starting with .)\n if (item.startsWith('.')) {\n continue;\n }\n\n const stat = fs.statSync(fullPath);\n if (stat.isDirectory()) {\n // Don't descend into a nested git repository (e.g. a clone under repositories/): it is a\n // separate project with its own version policy, NOT part of this monorepo's version lock.\n // The presence of a `.git` entry (dir for a real clone, file for a worktree/submodule)\n // marks a repo boundary — the same signal the AI guards use to scope to the current repo.\n if (fs.existsSync(path.join(fullPath, '.git'))) {\n continue;\n }\n files.push(...findPackageJsonFiles(fullPath, relativePath));\n } else if (item === 'package.json') {\n files.push(fullPath);\n }\n }\n\n return files;\n}\n\n/** Resolve catalogue pins before comparing authored direct versions. Published peers remain ranges. */\nclass VersionsLockedExecutor {\n async run(\n _options: ValidateVersionsLockedOptions,\n context: ExecutorContext,\n ): Promise<ExecutorResult> {\n if (new RuleGate().isDisabled(context.root, 'validate-versions-locked', true))\n return { success: true };\n const workspace = new DependencyWorkspace(context.root);\n const owners = [new DependencyOwner('.', workspace.rootManifest), ...workspace.owners];\n const versions = new Map<string, string>();\n const errors: string[] = [];\n for (const owner of owners) {\n if (!owner.manifest) continue;\n for (const section of [\n 'dependencies',\n 'devDependencies',\n 'optionalDependencies',\n ] as const) {\n for (const declaration of Object.entries(owner.manifest[section] ?? {})) {\n const name = declaration[0];\n const specifier = declaration[1];\n if (specifier.startsWith('workspace:') || specifier.startsWith('file:'))\n continue;\n const catalog = specifier.slice('catalog:'.length);\n const pin = specifier.startsWith('catalog:')\n ? (catalog\n ? workspace.catalog.catalogs?.[catalog]\n : workspace.catalog.catalog)?.[name]\n : specifier;\n const where = `${owner.directory}/package.json ${section}.${name}`;\n if (!pin || !new DependencyVersion().isExact(pin)) {\n errors.push(\n `${where}: ${specifier} must resolve to an exact locked version, found ${String(pin)}`,\n );\n continue;\n }\n const previous = versions.get(name);\n if (previous && previous !== pin)\n errors.push(\n `${where}: conflicting direct version ${pin}, already declared ${previous}`,\n );\n versions.set(name, pin);\n }\n }\n }\n if (errors.length)\n throw new RuleFailError(\n 'validate-versions-locked',\n errors.join('\\n'),\n undefined,\n undefined,\n [\n new Option(\n 'Use exact consistent direct versions or exact catalogue pins; preserve workspace:* for internal owners',\n true,\n ),\n ],\n );\n return { success: true };\n }\n}\n\nconst executor = new VersionsLockedExecutor();\nexport default executor.run.bind(executor);\n"]}
@@ -0,0 +1,14 @@
1
+ export declare class DependencyImport {
2
+ readonly specifier: string;
3
+ readonly line: number;
4
+ readonly runtime: boolean;
5
+ readonly unresolved: string;
6
+ constructor(specifier: string, line: number, runtime: boolean, unresolved?: string);
7
+ }
8
+ /** Parse syntax, including createRequire aliases; prose and relative imports are not packages. */
9
+ export declare class DependencyImports {
10
+ read(text: string, file: string): DependencyImport[];
11
+ packageName(specifier: string): string | undefined;
12
+ private collectAliases;
13
+ private specifiers;
14
+ }