@crossplatformai/dependency-graph 0.9.3 → 0.10.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.
Files changed (53) hide show
  1. package/README.md +36 -22
  2. package/dist/cli/index.d.ts +3 -0
  3. package/dist/cli/index.d.ts.map +1 -0
  4. package/dist/cli/pr-preview.d.ts +3 -0
  5. package/dist/cli/pr-preview.d.ts.map +1 -0
  6. package/dist/cli/validate-workflows.d.ts +3 -0
  7. package/dist/cli/validate-workflows.d.ts.map +1 -0
  8. package/dist/graph/analysis.d.ts +6 -0
  9. package/dist/graph/analysis.d.ts.map +1 -0
  10. package/dist/graph/builder.d.ts +3 -0
  11. package/dist/graph/builder.d.ts.map +1 -0
  12. package/dist/graph/traversal.d.ts +5 -0
  13. package/dist/graph/traversal.d.ts.map +1 -0
  14. package/dist/graph/types.d.ts +47 -0
  15. package/dist/graph/types.d.ts.map +1 -0
  16. package/dist/index-cli.js +1094 -0
  17. package/dist/index-cli.js.map +1 -0
  18. package/dist/index.d.ts +13 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +738 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/types/clients.d.ts +15 -0
  23. package/dist/types/clients.d.ts.map +1 -0
  24. package/dist/workflow/discovery.d.ts +4 -0
  25. package/dist/workflow/discovery.d.ts.map +1 -0
  26. package/dist/workflow/expected-paths.d.ts +13 -0
  27. package/dist/workflow/expected-paths.d.ts.map +1 -0
  28. package/dist/workflow/parser.d.ts +3 -0
  29. package/dist/workflow/parser.d.ts.map +1 -0
  30. package/dist/workflow/policy.d.ts +3 -0
  31. package/dist/workflow/policy.d.ts.map +1 -0
  32. package/dist/workflow/types.d.ts +34 -0
  33. package/dist/workflow/types.d.ts.map +1 -0
  34. package/dist/workflow/validator.d.ts +3 -0
  35. package/dist/workflow/validator.d.ts.map +1 -0
  36. package/dist/workspace/discovery.d.ts +12 -0
  37. package/dist/workspace/discovery.d.ts.map +1 -0
  38. package/dist/workspace/file-mapping.d.ts +4 -0
  39. package/dist/workspace/file-mapping.d.ts.map +1 -0
  40. package/dist/workspace/package-map.d.ts +12 -0
  41. package/dist/workspace/package-map.d.ts.map +1 -0
  42. package/package.json +49 -45
  43. package/src/cli/pr-preview.ts +0 -388
  44. package/src/cli/validate-workflows.ts +0 -847
  45. package/src/graph/analysis.ts +0 -147
  46. package/src/graph/builder.ts +0 -52
  47. package/src/graph/traversal.ts +0 -132
  48. package/src/graph/types.ts +0 -50
  49. package/src/index.test.ts +0 -94
  50. package/src/index.ts +0 -40
  51. package/src/types/clients.ts +0 -19
  52. package/src/workspace/discovery.ts +0 -94
  53. package/src/workspace/file-mapping.ts +0 -35
@@ -0,0 +1,1094 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/pr-preview.ts
4
+ import { readFileSync as readFileSync2 } from "fs";
5
+ import { resolve as resolve2 } from "path";
6
+ import { glob as glob2 } from "glob";
7
+ import { parse as parseYaml3 } from "yaml";
8
+
9
+ // src/graph/builder.ts
10
+ function buildDependencyGraph(packages) {
11
+ const graph = {
12
+ packages: /* @__PURE__ */ new Map(),
13
+ dependsOn: /* @__PURE__ */ new Map(),
14
+ dependedBy: /* @__PURE__ */ new Map()
15
+ };
16
+ for (const pkg of packages) {
17
+ graph.packages.set(pkg.name, pkg);
18
+ graph.dependsOn.set(pkg.name, /* @__PURE__ */ new Set());
19
+ graph.dependedBy.set(pkg.name, /* @__PURE__ */ new Set());
20
+ }
21
+ for (const pkg of packages) {
22
+ const allDeps = {
23
+ ...pkg.dependencies,
24
+ ...pkg.devDependencies
25
+ };
26
+ for (const depName of Object.keys(allDeps)) {
27
+ const matchedPkg = findMatchingPackage(depName, packages);
28
+ if (matchedPkg) {
29
+ graph.dependsOn.get(pkg.name).add(matchedPkg.name);
30
+ graph.dependedBy.get(matchedPkg.name).add(pkg.name);
31
+ }
32
+ }
33
+ }
34
+ return graph;
35
+ }
36
+ function findMatchingPackage(depName, packages) {
37
+ let match = packages.find((p) => p.name === depName);
38
+ if (match) return match;
39
+ match = packages.find((p) => p.name === `@repo/${depName}`);
40
+ if (match) return match;
41
+ const nameWithoutRepo = depName.replace(/^@repo\//, "");
42
+ match = packages.find((p) => p.name === nameWithoutRepo);
43
+ if (match) return match;
44
+ return void 0;
45
+ }
46
+
47
+ // src/graph/traversal.ts
48
+ function findAffectedPackages(startingPackages, graph, options = {}) {
49
+ const {
50
+ direction = "upstream",
51
+ maxDepth = Infinity,
52
+ filter,
53
+ respectAffectsUpstream = false
54
+ } = options;
55
+ const affected = new Set(startingPackages);
56
+ const queue = Array.from(
57
+ startingPackages
58
+ ).map((name) => ({ name, depth: 0 }));
59
+ const visited = /* @__PURE__ */ new Set();
60
+ while (queue.length > 0) {
61
+ const current = queue.shift();
62
+ if (visited.has(current.name)) continue;
63
+ visited.add(current.name);
64
+ if (current.depth >= maxDepth) {
65
+ continue;
66
+ }
67
+ const pkg = graph.packages.get(current.name);
68
+ if (!pkg) continue;
69
+ if (respectAffectsUpstream && direction === "upstream") {
70
+ const release = pkg.packageJson.release;
71
+ if (release && release.affectsUpstream === false) {
72
+ continue;
73
+ }
74
+ }
75
+ const nextPackages = /* @__PURE__ */ new Set();
76
+ if (direction === "upstream" || direction === "both") {
77
+ const upstream = graph.dependedBy.get(current.name) || /* @__PURE__ */ new Set();
78
+ upstream.forEach((p) => nextPackages.add(p));
79
+ }
80
+ if (direction === "downstream" || direction === "both") {
81
+ const downstream = graph.dependsOn.get(current.name) || /* @__PURE__ */ new Set();
82
+ downstream.forEach((p) => nextPackages.add(p));
83
+ }
84
+ for (const pkgName of nextPackages) {
85
+ const nextPkg = graph.packages.get(pkgName);
86
+ if (filter && nextPkg && !filter(nextPkg)) {
87
+ continue;
88
+ }
89
+ if (!affected.has(pkgName)) {
90
+ affected.add(pkgName);
91
+ queue.push({ name: pkgName, depth: current.depth + 1 });
92
+ }
93
+ }
94
+ }
95
+ return affected;
96
+ }
97
+
98
+ // src/workspace/discovery.ts
99
+ import { join, resolve } from "path";
100
+ async function discoverWorkspaces(rootDir, config) {
101
+ const workspaceConfig = await loadWorkspaceConfig(rootDir, config);
102
+ const packages = [];
103
+ for (const pattern of workspaceConfig.packages) {
104
+ if (pattern.startsWith("!")) continue;
105
+ const pkgDirs = await findPackageDirectories(rootDir, pattern, config);
106
+ for (const pkgDir of pkgDirs) {
107
+ const pkgJsonPath = join(pkgDir, "package.json");
108
+ try {
109
+ const pkgJsonContent = await config.fs.readFile(
110
+ pkgJsonPath,
111
+ "utf-8"
112
+ );
113
+ const pkgJson = JSON.parse(pkgJsonContent);
114
+ packages.push({
115
+ name: pkgJson.name,
116
+ version: pkgJson.version || "0.0.0",
117
+ path: pkgDir,
118
+ packageJson: pkgJson,
119
+ dependencies: pkgJson.dependencies || {},
120
+ devDependencies: pkgJson.devDependencies || {}
121
+ });
122
+ } catch {
123
+ continue;
124
+ }
125
+ }
126
+ }
127
+ return packages;
128
+ }
129
+ async function loadWorkspaceConfig(rootDir, config) {
130
+ const workspaceFilePath = join(rootDir, "pnpm-workspace.yaml");
131
+ try {
132
+ const content = await config.fs.readFile(
133
+ workspaceFilePath,
134
+ "utf-8"
135
+ );
136
+ const parsed = config.yaml.parse(content);
137
+ return parsed;
138
+ } catch {
139
+ return { packages: [] };
140
+ }
141
+ }
142
+ async function findPackageDirectories(rootDir, pattern, config) {
143
+ const matches = await config.glob.glob(pattern, {
144
+ cwd: rootDir,
145
+ absolute: false,
146
+ ignore: ["**/node_modules/**", "**/.next/**", "**/dist/**"]
147
+ });
148
+ return matches.map((match) => resolve(rootDir, match));
149
+ }
150
+
151
+ // src/workspace/package-map.ts
152
+ import { existsSync } from "fs";
153
+ import { join as join2, relative, sep } from "path";
154
+ function normalizeRelativePath(path) {
155
+ return path.split(sep).join("/");
156
+ }
157
+ function resolveWorkflowPath(relativePath, rootDir) {
158
+ if (!relativePath.startsWith("../")) {
159
+ return relativePath;
160
+ }
161
+ const segments = relativePath.split("/");
162
+ for (let index = 0; index < segments.length; index += 1) {
163
+ const candidateSegments = segments.slice(index);
164
+ if (candidateSegments.length === 0 || candidateSegments[0] === "..") {
165
+ continue;
166
+ }
167
+ const candidatePath = candidateSegments.join("/");
168
+ if (existsSync(join2(rootDir, candidatePath))) {
169
+ return candidatePath;
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+ function buildPackageMap(packages, rootDir) {
175
+ const packageMap = /* @__PURE__ */ new Map();
176
+ const workspaceRoots = /* @__PURE__ */ new Set();
177
+ for (const pkg of packages) {
178
+ const relativePath = normalizeRelativePath(relative(rootDir, pkg.path));
179
+ const workflowPath = resolveWorkflowPath(relativePath, rootDir);
180
+ packageMap.set(pkg.name, {
181
+ filesystemPath: relativePath,
182
+ workflowPath
183
+ });
184
+ if (!workflowPath) {
185
+ continue;
186
+ }
187
+ const [workspaceRoot] = workflowPath.split("/");
188
+ if (workspaceRoot) {
189
+ workspaceRoots.add(workspaceRoot);
190
+ }
191
+ }
192
+ return {
193
+ packageMap,
194
+ workspaceRoots
195
+ };
196
+ }
197
+
198
+ // src/workflow/policy.ts
199
+ var defaultWorkflowValidationPolicy = {
200
+ workflowFilePatterns: ["deploy-*.yml", "release-*.yml"],
201
+ allowedRootPaths: [
202
+ "package.json",
203
+ "pnpm-lock.yaml",
204
+ "pnpm-workspace.yaml",
205
+ "turbo.json"
206
+ ],
207
+ includeDevDependenciesForRootPackage: true,
208
+ includeDevDependenciesTransitively: false
209
+ };
210
+
211
+ // src/workflow/validator.ts
212
+ import { existsSync as existsSync4 } from "fs";
213
+ import { readFile } from "fs/promises";
214
+ import { glob } from "glob";
215
+ import { parse as parseYaml2 } from "yaml";
216
+
217
+ // src/workflow/discovery.ts
218
+ import { existsSync as existsSync2, readdirSync } from "fs";
219
+ import { join as join3 } from "path";
220
+ function patternToRegExp(pattern) {
221
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
222
+ return new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);
223
+ }
224
+ function discoverWorkflowTargets(rootDir, packages, policy) {
225
+ const workflowsDir = join3(rootDir, ".github/workflows");
226
+ if (!existsSync2(workflowsDir)) {
227
+ return [];
228
+ }
229
+ const { packageMap } = buildPackageMap(packages, rootDir);
230
+ const appPackages = packages.filter(
231
+ (pkg) => packageMap.get(pkg.name)?.workflowPath?.startsWith("apps/")
232
+ );
233
+ const bySlug = /* @__PURE__ */ new Map();
234
+ for (const pkg of appPackages) {
235
+ const relativePath = packageMap.get(pkg.name)?.workflowPath;
236
+ if (!relativePath) {
237
+ continue;
238
+ }
239
+ const slug = relativePath.split("/").at(-1);
240
+ if (slug) {
241
+ bySlug.set(slug, pkg.name);
242
+ }
243
+ }
244
+ const allowedPatterns = policy.workflowFilePatterns.map(patternToRegExp);
245
+ const files = readdirSync(workflowsDir).filter((file) => file.endsWith(".yml")).filter((file) => allowedPatterns.some((pattern) => pattern.test(file)));
246
+ return files.map((workflowFile) => {
247
+ const match = /^(?:deploy|release)-(.+)\.yml$/.exec(workflowFile);
248
+ const targetSlug = match?.[1] ?? workflowFile.replace(/\.yml$/, "");
249
+ return {
250
+ workflowFile,
251
+ workflowPath: `.github/workflows/${workflowFile}`,
252
+ targetSlug,
253
+ targetPackage: bySlug.get(targetSlug) ?? null
254
+ };
255
+ }).sort((a, b) => a.workflowFile.localeCompare(b.workflowFile));
256
+ }
257
+
258
+ // src/workflow/expected-paths.ts
259
+ function uniqueSorted(values) {
260
+ return Array.from(new Set(values)).sort();
261
+ }
262
+ function resolveWorkspaceDependency(dependencyName, packages) {
263
+ let match = packages.find((pkg) => pkg.name === dependencyName);
264
+ if (match) {
265
+ return match;
266
+ }
267
+ match = packages.find((pkg) => pkg.name === `@repo/${dependencyName}`);
268
+ if (match) {
269
+ return match;
270
+ }
271
+ const nameWithoutRepo = dependencyName.replace(/^@repo\//, "");
272
+ return packages.find((pkg) => pkg.name === nameWithoutRepo);
273
+ }
274
+ function collectWorkspaceDependencyNames(pkg, packages, visited, includeDevDependencies, includeDevDependenciesTransitively) {
275
+ const collected = /* @__PURE__ */ new Set();
276
+ const dependencyEntries = Object.entries(pkg.dependencies);
277
+ const devDependencyEntries = includeDevDependencies ? Object.entries(pkg.devDependencies) : [];
278
+ for (const [dependencyName] of [
279
+ ...dependencyEntries,
280
+ ...devDependencyEntries
281
+ ]) {
282
+ const dependency = resolveWorkspaceDependency(dependencyName, packages);
283
+ if (!dependency || visited.has(dependency.name)) {
284
+ continue;
285
+ }
286
+ visited.add(dependency.name);
287
+ collected.add(dependency.name);
288
+ const nestedDependencies = collectWorkspaceDependencyNames(
289
+ dependency,
290
+ packages,
291
+ visited,
292
+ includeDevDependenciesTransitively,
293
+ includeDevDependenciesTransitively
294
+ );
295
+ for (const nestedDependency of nestedDependencies) {
296
+ collected.add(nestedDependency);
297
+ }
298
+ }
299
+ return collected;
300
+ }
301
+ function getExpectedWorkflowPaths({
302
+ workflowTarget,
303
+ packages,
304
+ packageMap,
305
+ policy
306
+ }) {
307
+ const targetPackageName = workflowTarget.targetPackage;
308
+ if (!targetPackageName) {
309
+ return [];
310
+ }
311
+ const targetPackage = packages.find((pkg) => pkg.name === targetPackageName);
312
+ if (!targetPackage) {
313
+ return [];
314
+ }
315
+ const dependencyNames = collectWorkspaceDependencyNames(
316
+ targetPackage,
317
+ packages,
318
+ /* @__PURE__ */ new Set(),
319
+ policy.includeDevDependenciesForRootPackage,
320
+ policy.includeDevDependenciesTransitively
321
+ );
322
+ const expectedPaths = [];
323
+ const targetPackagePath = packageMap.get(targetPackageName)?.workflowPath;
324
+ if (targetPackagePath) {
325
+ expectedPaths.push(`${targetPackagePath}/**`);
326
+ }
327
+ for (const dependencyName of dependencyNames) {
328
+ const dependencyPath = packageMap.get(dependencyName)?.workflowPath;
329
+ if (dependencyPath) {
330
+ expectedPaths.push(`${dependencyPath}/**`);
331
+ }
332
+ }
333
+ return uniqueSorted(expectedPaths);
334
+ }
335
+
336
+ // src/workflow/parser.ts
337
+ import { existsSync as existsSync3, readFileSync } from "fs";
338
+ import { join as join4 } from "path";
339
+ import { parse as parseYaml } from "yaml";
340
+ function uniqueSorted2(values) {
341
+ return Array.from(new Set(values)).sort();
342
+ }
343
+ function parseWorkflowFile(workflowFile, rootDir) {
344
+ const workflowPath = join4(rootDir, ".github/workflows", workflowFile);
345
+ if (!existsSync3(workflowPath)) {
346
+ throw new Error(`Workflow file not found: ${workflowFile}`);
347
+ }
348
+ const content = readFileSync(workflowPath, "utf-8");
349
+ const workflow = parseYaml(content);
350
+ const pushPaths = workflow.on?.push?.paths ?? [];
351
+ const pullRequestPaths = workflow.on?.pull_request?.paths ?? [];
352
+ const parsedWorkflow = {
353
+ pushPaths: uniqueSorted2(pushPaths),
354
+ pullRequestPaths: uniqueSorted2(pullRequestPaths),
355
+ paths: uniqueSorted2([...pushPaths, ...pullRequestPaths])
356
+ };
357
+ if (workflow.name) {
358
+ parsedWorkflow.name = workflow.name;
359
+ }
360
+ return parsedWorkflow;
361
+ }
362
+
363
+ // src/workflow/validator.ts
364
+ function uniqueSorted3(values) {
365
+ return Array.from(new Set(values)).sort();
366
+ }
367
+ function buildBroadWildcards(workspaceRoots) {
368
+ const wildcards = /* @__PURE__ */ new Set();
369
+ for (const root of workspaceRoots) {
370
+ wildcards.add(`${root}/*`);
371
+ wildcards.add(`${root}/**`);
372
+ }
373
+ return wildcards;
374
+ }
375
+ function splitActualPaths(paths, workspaceRoots, allowedRootPaths, workflowPath) {
376
+ const workspacePaths = [];
377
+ const ignoredPaths = [];
378
+ for (const path of paths) {
379
+ if (path === workflowPath || allowedRootPaths.includes(path)) {
380
+ ignoredPaths.push(path);
381
+ continue;
382
+ }
383
+ const [rootSegment] = path.split("/");
384
+ if (rootSegment && workspaceRoots.has(rootSegment)) {
385
+ workspacePaths.push(path);
386
+ continue;
387
+ }
388
+ ignoredPaths.push(path);
389
+ }
390
+ return {
391
+ workspacePaths: uniqueSorted3(workspacePaths),
392
+ ignoredPaths: uniqueSorted3(ignoredPaths)
393
+ };
394
+ }
395
+ function isCoveredByExpectedPath(actualPath, expectedPaths) {
396
+ return expectedPaths.some((expectedPath) => {
397
+ if (expectedPath === actualPath) {
398
+ return true;
399
+ }
400
+ if (!expectedPath.endsWith("/**")) {
401
+ return false;
402
+ }
403
+ const expectedPrefix = expectedPath.slice(0, -3);
404
+ return actualPath.startsWith(`${expectedPrefix}/`);
405
+ });
406
+ }
407
+ function validateWorkflowResult(workflow, targetPackage, expectedPaths, actualPaths, broadWildcards) {
408
+ const issues = [];
409
+ const missing = expectedPaths.filter((path) => !actualPaths.includes(path));
410
+ const unnecessary = actualPaths.filter(
411
+ (path) => !isCoveredByExpectedPath(path, expectedPaths)
412
+ );
413
+ for (const path of missing) {
414
+ issues.push({
415
+ kind: "missing",
416
+ path,
417
+ message: `Missing path '${path}'`
418
+ });
419
+ }
420
+ for (const path of unnecessary) {
421
+ issues.push({
422
+ kind: "unnecessary",
423
+ path,
424
+ message: `Unnecessary path '${path}'`
425
+ });
426
+ }
427
+ for (const path of actualPaths) {
428
+ if (broadWildcards.has(path)) {
429
+ issues.push({
430
+ kind: "broad-wildcard",
431
+ path,
432
+ message: `Uses broad wildcard '${path}' which triggers on all workspace changes under that root`
433
+ });
434
+ }
435
+ }
436
+ return {
437
+ workflow,
438
+ targetPackage,
439
+ valid: issues.length === 0,
440
+ expectedPaths,
441
+ actualPaths,
442
+ missing,
443
+ unnecessary,
444
+ issues
445
+ };
446
+ }
447
+ async function validateWorkflows(rootDir, policyOverrides) {
448
+ const discoveredPackages = await discoverWorkspaces(rootDir, {
449
+ fs: {
450
+ readFile: (path, encoding) => readFile(path, encoding),
451
+ exists: (path) => Promise.resolve(existsSync4(path))
452
+ },
453
+ glob: {
454
+ glob: (pattern, options) => glob(pattern, options)
455
+ },
456
+ yaml: {
457
+ parse: (content) => parseYaml2(content)
458
+ }
459
+ });
460
+ const policy = {
461
+ ...defaultWorkflowValidationPolicy,
462
+ ...policyOverrides,
463
+ allowedRootPaths: uniqueSorted3([
464
+ ...defaultWorkflowValidationPolicy.allowedRootPaths,
465
+ ...policyOverrides?.allowedRootPaths ?? []
466
+ ])
467
+ };
468
+ const { packageMap, workspaceRoots } = buildPackageMap(
469
+ discoveredPackages,
470
+ rootDir
471
+ );
472
+ const workflowTargets = discoverWorkflowTargets(
473
+ rootDir,
474
+ discoveredPackages,
475
+ policy
476
+ );
477
+ const broadWildcards = buildBroadWildcards(workspaceRoots);
478
+ return workflowTargets.map((workflowTarget) => {
479
+ if (!workflowTarget.targetPackage) {
480
+ return {
481
+ workflow: workflowTarget.workflowFile,
482
+ targetPackage: workflowTarget.targetSlug,
483
+ valid: false,
484
+ expectedPaths: [],
485
+ actualPaths: [],
486
+ missing: [],
487
+ unnecessary: [],
488
+ issues: [
489
+ {
490
+ kind: "config-error",
491
+ message: `Could not resolve workflow target package for '${workflowTarget.workflowFile}'`
492
+ }
493
+ ]
494
+ };
495
+ }
496
+ try {
497
+ const parsedWorkflow = parseWorkflowFile(
498
+ workflowTarget.workflowFile,
499
+ rootDir
500
+ );
501
+ if (parsedWorkflow.paths.length === 0) {
502
+ return {
503
+ workflow: workflowTarget.workflowFile,
504
+ targetPackage: workflowTarget.targetPackage,
505
+ valid: true,
506
+ expectedPaths: [],
507
+ actualPaths: [],
508
+ missing: [],
509
+ unnecessary: [],
510
+ issues: []
511
+ };
512
+ }
513
+ const { workspacePaths: actualPaths } = splitActualPaths(
514
+ parsedWorkflow.paths,
515
+ workspaceRoots,
516
+ policy.allowedRootPaths,
517
+ workflowTarget.workflowPath
518
+ );
519
+ const expectedPaths = getExpectedWorkflowPaths({
520
+ workflowTarget,
521
+ packages: discoveredPackages,
522
+ packageMap,
523
+ policy
524
+ });
525
+ return validateWorkflowResult(
526
+ workflowTarget.workflowFile,
527
+ workflowTarget.targetPackage,
528
+ expectedPaths,
529
+ actualPaths,
530
+ broadWildcards
531
+ );
532
+ } catch (error) {
533
+ return {
534
+ workflow: workflowTarget.workflowFile,
535
+ targetPackage: workflowTarget.targetPackage,
536
+ valid: false,
537
+ expectedPaths: [],
538
+ actualPaths: [],
539
+ missing: [],
540
+ unnecessary: [],
541
+ issues: [
542
+ {
543
+ kind: "parse-error",
544
+ message: error instanceof Error ? error.message : String(error)
545
+ }
546
+ ]
547
+ };
548
+ }
549
+ });
550
+ }
551
+
552
+ // src/cli/pr-preview.ts
553
+ var WORKFLOW_MAPPING = {
554
+ "deploy-web.yml": "web",
555
+ "deploy-api-origin.yml": "api-origin",
556
+ "deploy-api-edge.yml": "api-edge",
557
+ "release-mobile.yml": "mobile",
558
+ "release-desktop.yml": "desktop",
559
+ "release-cli.yml": "cli"
560
+ };
561
+ var PLATFORM_INDICATORS = [
562
+ {
563
+ platform: "cloudflare-workers",
564
+ indicators: [{ file: "wrangler.toml" }]
565
+ },
566
+ {
567
+ platform: "expo",
568
+ indicators: [{ file: "app.json" }, { file: "eas.json" }]
569
+ },
570
+ {
571
+ platform: "npm-package",
572
+ indicators: [{ field: "bin" }]
573
+ },
574
+ {
575
+ platform: "electron",
576
+ indicators: [
577
+ { dependency: "electron" },
578
+ { dependency: "electron-builder" }
579
+ ]
580
+ },
581
+ {
582
+ platform: "next.js",
583
+ indicators: [
584
+ { file: "next.config.js" },
585
+ { file: "next.config.mjs" },
586
+ { file: "next.config.ts" },
587
+ { dependency: "next" }
588
+ ]
589
+ },
590
+ {
591
+ platform: "node.js",
592
+ indicators: [
593
+ { field: "start" }
594
+ // has start script
595
+ ]
596
+ }
597
+ ];
598
+ var DEFAULT_APP_DIRECTORIES = ["apps"];
599
+ function isDeployableApp(pkg) {
600
+ const isInAppDirectory = DEFAULT_APP_DIRECTORIES.some(
601
+ (dir) => pkg.path.includes(`/${dir}/`) || pkg.path.endsWith(`/${dir}`)
602
+ );
603
+ if (!isInAppDirectory) {
604
+ return { deployable: false };
605
+ }
606
+ for (const platformDetection of PLATFORM_INDICATORS) {
607
+ const hasIndicators = platformDetection.indicators.some((indicator) => {
608
+ if (indicator.file) {
609
+ try {
610
+ const filePath = resolve2(pkg.path, indicator.file);
611
+ readFileSync2(filePath, "utf-8");
612
+ return true;
613
+ } catch {
614
+ return false;
615
+ }
616
+ }
617
+ if (indicator.field) {
618
+ const scripts = pkg.packageJson.scripts;
619
+ if (indicator.field === "start" && scripts?.start) {
620
+ return true;
621
+ }
622
+ const packageJsonField = pkg.packageJson[indicator.field];
623
+ if (indicator.field !== "start" && packageJsonField) {
624
+ return true;
625
+ }
626
+ }
627
+ if (indicator.dependency) {
628
+ return !!(pkg.dependencies[indicator.dependency] || pkg.devDependencies[indicator.dependency]);
629
+ }
630
+ return false;
631
+ });
632
+ if (hasIndicators) {
633
+ return { deployable: true, platform: platformDetection.platform };
634
+ }
635
+ }
636
+ return { deployable: false };
637
+ }
638
+ async function getChangedFiles() {
639
+ const { execSync } = await import("child_process");
640
+ try {
641
+ let baseBranch = "production";
642
+ try {
643
+ execSync("git rev-parse production", {
644
+ encoding: "utf-8",
645
+ stdio: "pipe"
646
+ });
647
+ } catch {
648
+ baseBranch = "origin/production";
649
+ }
650
+ const output = execSync(`git diff --name-status ${baseBranch}...HEAD`, {
651
+ encoding: "utf-8"
652
+ });
653
+ return output.trim().split("\n").filter((line) => line).map((line) => {
654
+ const [status, path] = line.split(" ");
655
+ return {
656
+ path: path ?? "",
657
+ status: status === "D" ? "deleted" : status === "A" ? "added" : "modified"
658
+ };
659
+ }).filter((file) => file.path !== "");
660
+ } catch {
661
+ console.error(
662
+ "Failed to get changed files. Ensure you are on a branch with commits compared to production."
663
+ );
664
+ process.exit(1);
665
+ }
666
+ }
667
+ async function runPrPreview() {
668
+ try {
669
+ const rootDir = resolve2(process.cwd());
670
+ const changedFiles = await getChangedFiles();
671
+ console.log(
672
+ `
673
+ \u{1F4E6} Release Preview - Changed Files: ${changedFiles.length}
674
+ `
675
+ );
676
+ changedFiles.forEach((file) => {
677
+ console.log(` ${file.status === "deleted" ? "\u274C" : "\u{1F4DD}"} ${file.path}`);
678
+ });
679
+ const packages = await discoverWorkspaces(rootDir, {
680
+ fs: {
681
+ readFile: (path) => {
682
+ try {
683
+ return Promise.resolve(readFileSync2(path, "utf-8"));
684
+ } catch {
685
+ return Promise.reject(new Error(`Failed to read file: ${path}`));
686
+ }
687
+ },
688
+ exists: (path) => {
689
+ try {
690
+ readFileSync2(path, "utf-8");
691
+ return Promise.resolve(true);
692
+ } catch {
693
+ return Promise.resolve(false);
694
+ }
695
+ }
696
+ },
697
+ glob: {
698
+ glob: async (pattern, options) => glob2(pattern, options)
699
+ },
700
+ yaml: {
701
+ parse: (content) => parseYaml3(content)
702
+ }
703
+ });
704
+ const graph = buildDependencyGraph(packages);
705
+ const changedPackages = /* @__PURE__ */ new Set();
706
+ for (const file of changedFiles) {
707
+ if (file.status === "deleted") continue;
708
+ const pkg = packages.find((p) => {
709
+ const relativePkgPath = p.path.replace(rootDir + "/", "");
710
+ return file.path.startsWith(relativePkgPath);
711
+ });
712
+ if (pkg) {
713
+ changedPackages.add(pkg.name);
714
+ }
715
+ }
716
+ const changedWorkflows = changedFiles.filter(
717
+ (f) => f.path.startsWith(".github/workflows/")
718
+ );
719
+ const workflowAffectedApps = /* @__PURE__ */ new Set();
720
+ for (const workflow of changedWorkflows) {
721
+ const workflowName = workflow.path.split("/").pop();
722
+ if (workflowName && WORKFLOW_MAPPING[workflowName]) {
723
+ workflowAffectedApps.add(WORKFLOW_MAPPING[workflowName]);
724
+ }
725
+ }
726
+ console.log(
727
+ `
728
+ \u{1F4E6} Changed packages: ${Array.from(changedPackages).join(", ") || "none"}
729
+ `
730
+ );
731
+ if (changedPackages.size === 0) {
732
+ console.log("\n\u2728 No packages changed - no deployments needed\n");
733
+ return;
734
+ }
735
+ const affected = findAffectedPackages(changedPackages, graph, {
736
+ direction: "upstream",
737
+ respectAffectsUpstream: true
738
+ });
739
+ const allDeployableApps = packages.map((pkg) => {
740
+ const detection = isDeployableApp(pkg);
741
+ return detection.deployable ? { name: pkg.name, pkg, platform: detection.platform } : null;
742
+ }).filter(
743
+ (item) => item !== null
744
+ );
745
+ const affectedApps = allDeployableApps.filter(
746
+ (app) => affected.has(app.name) || workflowAffectedApps.has(app.name)
747
+ );
748
+ const unaffectedApps = allDeployableApps.filter(
749
+ (app) => !affected.has(app.name) && !workflowAffectedApps.has(app.name)
750
+ );
751
+ const getAppCategory = (platform) => {
752
+ switch (platform) {
753
+ case "next.js":
754
+ case "cloudflare-workers":
755
+ case "node.js":
756
+ return "deploy";
757
+ case "expo":
758
+ case "electron":
759
+ case "npm-package":
760
+ return "release";
761
+ default:
762
+ return "deploy";
763
+ }
764
+ };
765
+ const getAppIcon = (platform) => {
766
+ switch (platform) {
767
+ case "next.js":
768
+ case "cloudflare-workers":
769
+ case "node.js":
770
+ return "\u{1F310}";
771
+ case "expo":
772
+ return "\u{1F4F1}";
773
+ case "electron":
774
+ return "\u{1F5A5}\uFE0F";
775
+ case "npm-package":
776
+ return "\u26A1";
777
+ default:
778
+ return "\u{1F310}";
779
+ }
780
+ };
781
+ const affectedDeploys = affectedApps.filter(
782
+ (app) => getAppCategory(app.platform) === "deploy"
783
+ );
784
+ const affectedReleases = affectedApps.filter(
785
+ (app) => getAppCategory(app.platform) === "release"
786
+ );
787
+ console.log(`
788
+ \u{1F680} PR Preview
789
+ `);
790
+ if (affectedApps.length === 0) {
791
+ console.log("No apps affected by changes.\n");
792
+ } else {
793
+ if (affectedDeploys.length > 0) {
794
+ console.log("\u{1F4CB} Apps that will be DEPLOYED:");
795
+ for (const item of affectedDeploys) {
796
+ const platformDisplay = item.platform === "generic" ? "" : ` (${item.platform})`;
797
+ const icon = getAppIcon(item.platform);
798
+ console.log(`${icon} ${item.name}${platformDisplay}`);
799
+ }
800
+ console.log("");
801
+ }
802
+ if (affectedReleases.length > 0) {
803
+ console.log("\u{1F4CB} Apps that will be RELEASED:");
804
+ for (const item of affectedReleases) {
805
+ const platformDisplay = item.platform === "generic" ? "" : ` (${item.platform})`;
806
+ const icon = getAppIcon(item.platform);
807
+ console.log(`${icon} ${item.name}${platformDisplay}`);
808
+ }
809
+ console.log("");
810
+ }
811
+ }
812
+ if (unaffectedApps.length > 0) {
813
+ console.log(`\u{1F4CB} Apps that will NOT be affected:`);
814
+ for (const item of unaffectedApps) {
815
+ const platformDisplay = item.platform === "generic" ? "" : ` (${item.platform})`;
816
+ console.log(`\u23ED\uFE0F ${item.name}${platformDisplay}`);
817
+ }
818
+ console.log("");
819
+ }
820
+ console.log(`Legend:`);
821
+ console.log(`\u{1F310} = Deploy (web-based, instant updates)`);
822
+ console.log(`\u{1F4F1} = Release (mobile app, user installs)`);
823
+ console.log(`\u{1F5A5}\uFE0F = Release (desktop app, user installs)`);
824
+ console.log(`\u26A1 = Release (CLI tool, user installs)`);
825
+ console.log(`\u23ED\uFE0F = Unaffected (no changes needed)`);
826
+ console.log(`\u{1F4DD} = File changed`);
827
+ console.log(`\u274C = File deleted
828
+ `);
829
+ } catch (error) {
830
+ console.error(
831
+ "Error:",
832
+ error instanceof Error ? error.message : String(error)
833
+ );
834
+ process.exit(1);
835
+ }
836
+ }
837
+ if (import.meta.url === new URL(process.argv[1] ?? "", "file:").href) {
838
+ void runPrPreview();
839
+ }
840
+
841
+ // src/cli/validate-workflows.ts
842
+ import { existsSync as existsSync5, readFileSync as readFileSync3, readdirSync as readdirSync2 } from "fs";
843
+ import { join as join5, resolve as resolve3 } from "path";
844
+ import { parse as parseYaml4 } from "yaml";
845
+ function discoverPnpmWorkflows(rootDir) {
846
+ const workflowsDir = join5(rootDir, ".github/workflows");
847
+ if (!existsSync5(workflowsDir)) {
848
+ return [];
849
+ }
850
+ const workflows = [];
851
+ const files = readdirSync2(workflowsDir).filter(
852
+ (file) => file.endsWith(".yml")
853
+ );
854
+ for (const file of files) {
855
+ const content = readFileSync3(join5(workflowsDir, file), "utf-8");
856
+ if (content.includes("pnpm/action-setup")) {
857
+ workflows.push(file);
858
+ }
859
+ }
860
+ return workflows;
861
+ }
862
+ function discoverPnpmDockerfiles(rootDir) {
863
+ const dockerfiles = [];
864
+ for (const entry of readdirSync2(rootDir)) {
865
+ if (!entry.startsWith("Dockerfile")) {
866
+ continue;
867
+ }
868
+ const content = readFileSync3(join5(rootDir, entry), "utf-8");
869
+ if (content.includes("pnpm@")) {
870
+ dockerfiles.push(entry);
871
+ }
872
+ }
873
+ const appsDir = join5(rootDir, "apps");
874
+ if (!existsSync5(appsDir)) {
875
+ return dockerfiles;
876
+ }
877
+ for (const entry of readdirSync2(appsDir, { withFileTypes: true })) {
878
+ if (!entry.isDirectory()) {
879
+ continue;
880
+ }
881
+ const dockerfilePath = join5(appsDir, entry.name, "Dockerfile");
882
+ if (!existsSync5(dockerfilePath)) {
883
+ continue;
884
+ }
885
+ const content = readFileSync3(dockerfilePath, "utf-8");
886
+ if (content.includes("pnpm@")) {
887
+ dockerfiles.push(`apps/${entry.name}/Dockerfile`);
888
+ }
889
+ }
890
+ return dockerfiles;
891
+ }
892
+ function getExpectedPnpmVersion(rootDir) {
893
+ const packageJson = JSON.parse(
894
+ readFileSync3(join5(rootDir, "package.json"), "utf-8")
895
+ );
896
+ const packageManager = packageJson.packageManager;
897
+ if (!packageManager?.startsWith("pnpm@")) {
898
+ throw new Error("packageManager field must specify pnpm version");
899
+ }
900
+ return packageManager.replace("pnpm@", "");
901
+ }
902
+ function checkWorkflowPnpmVersion(workflowFile, rootDir) {
903
+ const workflowPath = join5(rootDir, ".github/workflows", workflowFile);
904
+ if (!existsSync5(workflowPath)) {
905
+ return { valid: true };
906
+ }
907
+ const content = readFileSync3(workflowPath, "utf-8");
908
+ const workflow = parseYaml4(content);
909
+ for (const job of Object.values(workflow.jobs ?? {})) {
910
+ for (const step of job.steps ?? []) {
911
+ if (!step.uses?.startsWith("pnpm/action-setup")) {
912
+ continue;
913
+ }
914
+ const version = step.with?.version;
915
+ if (version !== void 0 && !/^\d+$/.test(String(version))) {
916
+ return {
917
+ valid: false,
918
+ issue: `Hardcoded pnpm version '${version}' - remove 'version' key to auto-detect from packageManager`
919
+ };
920
+ }
921
+ }
922
+ }
923
+ return { valid: true };
924
+ }
925
+ function checkDockerfilePnpmVersion(dockerfile, expectedVersion, rootDir) {
926
+ const dockerfilePath = join5(rootDir, dockerfile);
927
+ if (!existsSync5(dockerfilePath)) {
928
+ return { valid: true };
929
+ }
930
+ const content = readFileSync3(dockerfilePath, "utf-8");
931
+ const matches = content.matchAll(/npm install -g pnpm@([\d.]+)/g);
932
+ for (const match of matches) {
933
+ if (match[1] !== expectedVersion) {
934
+ return {
935
+ valid: false,
936
+ issue: `${dockerfile} uses pnpm@${match[1]} but package.json specifies pnpm@${expectedVersion}`
937
+ };
938
+ }
939
+ }
940
+ return { valid: true };
941
+ }
942
+ function validatePnpmVersions(rootDir) {
943
+ const result = {
944
+ valid: true,
945
+ workflowIssues: [],
946
+ dockerfileIssues: []
947
+ };
948
+ for (const workflowFile of discoverPnpmWorkflows(rootDir)) {
949
+ const check = checkWorkflowPnpmVersion(workflowFile, rootDir);
950
+ if (!check.valid && check.issue) {
951
+ result.valid = false;
952
+ result.workflowIssues.push({
953
+ workflow: workflowFile,
954
+ issue: check.issue
955
+ });
956
+ }
957
+ }
958
+ const expectedVersion = getExpectedPnpmVersion(rootDir);
959
+ for (const dockerfile of discoverPnpmDockerfiles(rootDir)) {
960
+ const check = checkDockerfilePnpmVersion(
961
+ dockerfile,
962
+ expectedVersion,
963
+ rootDir
964
+ );
965
+ if (!check.valid && check.issue) {
966
+ result.valid = false;
967
+ result.dockerfileIssues.push({ dockerfile, issue: check.issue });
968
+ }
969
+ }
970
+ return result;
971
+ }
972
+ function printResult(result) {
973
+ const icon = result.valid ? "\u2705" : "\u274C";
974
+ console.log(`
975
+ ${icon} ${result.workflow} (${result.targetPackage})`);
976
+ if (result.valid) {
977
+ console.log(" All paths match dependencies");
978
+ return;
979
+ }
980
+ const extraIssues = result.issues.filter(
981
+ (issue) => issue.kind !== "missing" && issue.kind !== "unnecessary"
982
+ );
983
+ if (extraIssues.length > 0) {
984
+ console.log(" Issues:");
985
+ for (const issue of extraIssues) {
986
+ console.log(` \u26A0\uFE0F ${issue.message}`);
987
+ }
988
+ }
989
+ if (result.missing.length > 0) {
990
+ console.log(" Missing paths:");
991
+ for (const path of result.missing) {
992
+ console.log(` - ${path}`);
993
+ }
994
+ }
995
+ if (result.unnecessary.length > 0) {
996
+ console.log(" Unnecessary paths:");
997
+ for (const path of result.unnecessary) {
998
+ console.log(` - ${path}`);
999
+ }
1000
+ }
1001
+ }
1002
+ async function runValidateWorkflows() {
1003
+ const rootDir = resolve3(process.cwd());
1004
+ let hasErrors = false;
1005
+ console.log(
1006
+ "\u{1F50D} Validating GitHub Actions workflows against dependencies...\n"
1007
+ );
1008
+ const results = await validateWorkflows(rootDir);
1009
+ console.log(`Found ${results.length} workflow(s) to validate
1010
+ `);
1011
+ if (results.length === 0) {
1012
+ console.log("No deploy-*.yml or release-*.yml workflows found.\n");
1013
+ }
1014
+ for (const result of results) {
1015
+ printResult(result);
1016
+ }
1017
+ const validCount = results.filter((result) => result.valid).length;
1018
+ const invalidCount = results.length - validCount;
1019
+ console.log("\n" + "=".repeat(60));
1020
+ console.log(
1021
+ `
1022
+ \u{1F4CA} Path validation: ${validCount} valid, ${invalidCount} invalid
1023
+ `
1024
+ );
1025
+ if (invalidCount > 0) {
1026
+ console.log("\u274C Some workflows need updates to match dependencies");
1027
+ console.log("\nTo fix:");
1028
+ console.log("1. Update workflow path filters to match missing paths");
1029
+ console.log("2. Remove unnecessary paths");
1030
+ console.log("3. Replace broad workspace wildcards with specific paths\n");
1031
+ hasErrors = true;
1032
+ } else if (results.length > 0) {
1033
+ console.log("\u2705 All workflows match their dependencies!\n");
1034
+ }
1035
+ console.log("=".repeat(60));
1036
+ console.log("\n\u{1F50D} Validating pnpm version consistency...\n");
1037
+ const pnpmResult = validatePnpmVersions(rootDir);
1038
+ if (!pnpmResult.valid) {
1039
+ console.log("\u274C PNPM version issues found:\n");
1040
+ for (const { workflow, issue } of pnpmResult.workflowIssues) {
1041
+ console.log(` \u26A0\uFE0F ${workflow}: ${issue}`);
1042
+ }
1043
+ for (const { issue } of pnpmResult.dockerfileIssues) {
1044
+ console.log(` \u26A0\uFE0F ${issue}`);
1045
+ }
1046
+ console.log("\nTo fix:");
1047
+ console.log(
1048
+ "1. Remove hardcoded pnpm versions from workflows (let pnpm/action-setup auto-detect from packageManager)"
1049
+ );
1050
+ console.log(
1051
+ "2. Update Dockerfile pnpm versions to match package.json packageManager field\n"
1052
+ );
1053
+ hasErrors = true;
1054
+ } else {
1055
+ console.log("\u2705 PNPM versions are consistent!\n");
1056
+ }
1057
+ if (hasErrors) {
1058
+ process.exit(1);
1059
+ }
1060
+ }
1061
+ if (import.meta.url === new URL(process.argv[1] ?? "", "file:").href) {
1062
+ void runValidateWorkflows();
1063
+ }
1064
+
1065
+ // src/cli/index.ts
1066
+ function printHelp() {
1067
+ console.log(`dependency-graph <command>
1068
+
1069
+ Commands:
1070
+ pr-preview Show affected deploys and releases for the current branch
1071
+ validate-workflows Validate workflow path filters and pnpm version consistency`);
1072
+ }
1073
+ async function main() {
1074
+ const command = process.argv[2];
1075
+ switch (command) {
1076
+ case "pr-preview":
1077
+ await runPrPreview();
1078
+ return;
1079
+ case "validate-workflows":
1080
+ await runValidateWorkflows();
1081
+ return;
1082
+ case "--help":
1083
+ case "-h":
1084
+ case void 0:
1085
+ printHelp();
1086
+ return;
1087
+ default:
1088
+ console.error(`Unknown dependency-graph command: ${command}`);
1089
+ printHelp();
1090
+ process.exit(1);
1091
+ }
1092
+ }
1093
+ void main();
1094
+ //# sourceMappingURL=index-cli.js.map