@package-pal/core 0.0.9 → 0.0.11

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 (60) hide show
  1. package/index.d.ts +4 -0
  2. package/index.d.ts.map +1 -1
  3. package/index.js +390 -433
  4. package/index.js.map +26 -30
  5. package/lib/api.d.ts +1 -1
  6. package/lib/api.d.ts.map +1 -1
  7. package/lib/configuration/functions/load-config.d.ts.map +1 -1
  8. package/lib/configuration/functions/parse-config.d.ts +1 -0
  9. package/lib/configuration/functions/parse-config.d.ts.map +1 -1
  10. package/lib/configuration/schemas/config.d.ts +5 -75
  11. package/lib/configuration/schemas/config.d.ts.map +1 -1
  12. package/lib/graph/functions/dfs-traverse-graph-paths.d.ts +8 -1
  13. package/lib/graph/functions/dfs-traverse-graph-paths.d.ts.map +1 -1
  14. package/lib/graph/functions/extract-subgraph.d.ts.map +1 -1
  15. package/lib/graph/functions/generate-graphs.d.ts.map +1 -1
  16. package/lib/graph/functions/generate-topological-sorted-groups.d.ts +1 -1
  17. package/lib/graph/functions/generate-topological-sorted-groups.d.ts.map +1 -1
  18. package/lib/package/functions/load-packages.d.ts +2 -1
  19. package/lib/package/functions/load-packages.d.ts.map +1 -1
  20. package/lib/package/functions/run-for-each-package.d.ts.map +1 -1
  21. package/lib/package/functions/scan-glob-pattern-paths.d.ts.map +1 -1
  22. package/lib/package/types/package-adapter.d.ts +36 -0
  23. package/lib/package/types/package-adapter.d.ts.map +1 -0
  24. package/lib/package/types/package-data.d.ts +1 -0
  25. package/lib/package/types/package-data.d.ts.map +1 -1
  26. package/lib/process/functions/get-commands-for-shell.d.ts +5 -1
  27. package/lib/process/functions/get-commands-for-shell.d.ts.map +1 -1
  28. package/lib/process/functions/get-line-buffered-writer.d.ts +7 -1
  29. package/lib/process/functions/get-line-buffered-writer.d.ts.map +1 -1
  30. package/lib/process/functions/get-shell.d.ts.map +1 -1
  31. package/lib/process/functions/parse-ps-shell-flags.d.ts.map +1 -1
  32. package/lib/process/functions/read-stream.d.ts.map +1 -1
  33. package/lib/process/functions/run-subprocess.d.ts +2 -1
  34. package/lib/process/functions/run-subprocess.d.ts.map +1 -1
  35. package/lib/process/functions/strip-clixml.d.ts +6 -0
  36. package/lib/process/functions/strip-clixml.d.ts.map +1 -0
  37. package/lib/types/bump-package-version-options.d.ts +2 -0
  38. package/lib/types/bump-package-version-options.d.ts.map +1 -1
  39. package/lib/types/get-package-data-options.d.ts +2 -0
  40. package/lib/types/get-package-data-options.d.ts.map +1 -1
  41. package/lib/watch/functions/dedupe-shared-paths.d.ts +3 -0
  42. package/lib/watch/functions/dedupe-shared-paths.d.ts.map +1 -0
  43. package/lib/watch/functions/filter-files-modified-since.d.ts +1 -1
  44. package/lib/watch/functions/filter-files-modified-since.d.ts.map +1 -1
  45. package/lib/watch/functions/get-change-logic.d.ts +1 -1
  46. package/lib/watch/functions/get-change-logic.d.ts.map +1 -1
  47. package/lib/watch/functions/watch-package-changes.d.ts.map +1 -1
  48. package/lib/watch/types/dedupe-paths-by.d.ts +7 -0
  49. package/lib/watch/types/dedupe-paths-by.d.ts.map +1 -0
  50. package/package.json +6 -7
  51. package/lib/package/functions/parse-package.d.ts +0 -3
  52. package/lib/package/functions/parse-package.d.ts.map +0 -1
  53. package/lib/package/functions/scan-packages.d.ts +0 -4
  54. package/lib/package/functions/scan-packages.d.ts.map +0 -1
  55. package/lib/package/functions/update-package-version.d.ts +0 -5
  56. package/lib/package/functions/update-package-version.d.ts.map +0 -1
  57. package/lib/process/functions/escape-shell-arg.d.ts +0 -8
  58. package/lib/process/functions/escape-shell-arg.d.ts.map +0 -1
  59. package/lib/watch/functions/normalise-pattern-separators.d.ts +0 -2
  60. package/lib/watch/functions/normalise-pattern-separators.d.ts.map +0 -1
package/index.js CHANGED
@@ -9,8 +9,11 @@ var BumpVersionType = {
9
9
  Prepatch: "prepatch",
10
10
  Prerelease: "prerelease"
11
11
  };
12
+ // packages/core/src/lib/package/types/package-adapter.ts
13
+ class PackageAdapter {
14
+ }
12
15
  // packages/core/src/lib/api.ts
13
- import { isDefined as isDefined5 } from "@package-pal/util";
16
+ import { isDefined as isDefined4 } from "@package-pal/util";
14
17
 
15
18
  // packages/core/src/lib/configuration/functions/check-bun.ts
16
19
  var checkBun = () => {
@@ -20,9 +23,9 @@ var checkBun = () => {
20
23
  };
21
24
 
22
25
  // packages/core/src/lib/configuration/functions/load-config.ts
23
- import { styleText } from "util";
24
26
  import { dirname as dirname3 } from "path";
25
27
  import { cwd } from "process";
28
+ import { styleText } from "util";
26
29
  import {
27
30
  deepMergeDefined,
28
31
  formatSimpleLogObject,
@@ -85,6 +88,11 @@ var LogLevel = z3.enum([
85
88
  "silent"
86
89
  ]);
87
90
  var Config = z3.object({
91
+ adapter: z3.optional(z3.enum([
92
+ "package-json",
93
+ "msbuild",
94
+ "auto"
95
+ ])),
88
96
  packages: z3.optional(z3.union([z3.string(), z3.array(z3.string())])),
89
97
  version: z3.optional(z3.object({
90
98
  preId: z3.optional(z3.string()),
@@ -210,6 +218,7 @@ var searchConfigPath = async (pathOverride) => {
210
218
 
211
219
  // packages/core/src/lib/configuration/functions/load-config.ts
212
220
  var defaultConfig = {
221
+ adapter: "auto",
213
222
  packages: "packages/*",
214
223
  version: {
215
224
  preId: "",
@@ -241,7 +250,7 @@ var defaultConfig = {
241
250
  var loadConfig = async (overrideConfigPath) => {
242
251
  const path = await searchConfigPath(overrideConfigPath);
243
252
  if (!path) {
244
- defaultConfig.logger.info("No config file found. Defaults will be applied.");
253
+ defaultConfig.logger.debug("No config file found. Defaults will be applied.");
245
254
  return {
246
255
  config: defaultConfig,
247
256
  rootDir: cwd()
@@ -268,32 +277,16 @@ ${styleText("dim", formatSimpleLogObject(activatedConfig))}`);
268
277
  // packages/core/src/lib/graph/functions/generate-graphs.ts
269
278
  import { styleText as styleText2 } from "util";
270
279
  import { assertDefined as assertDefined2 } from "@package-pal/util";
271
-
272
- // packages/core/src/lib/package/types/dependencies-field.ts
273
- var DependenciesField = {
274
- Dependencies: "dependencies",
275
- DevDependencies: "devDependencies",
276
- PeerDependencies: "peerDependencies",
277
- OptionalDependencies: "optionalDependencies"
278
- };
279
-
280
- // packages/core/src/lib/graph/functions/generate-graphs.ts
281
280
  var trackPackageEntryDependencies = ({
282
281
  trackedDependencies,
283
282
  packageNames,
284
283
  packageData
285
284
  }) => {
286
- const iterateEntries = Object.values(DependenciesField).map((field) => packageData[field]);
287
- for (const packageEntries of iterateEntries) {
288
- if (!packageEntries) {
285
+ for (const trackPackageName of packageData.localDependencies ?? []) {
286
+ if (!packageNames.has(trackPackageName)) {
289
287
  continue;
290
288
  }
291
- for (const trackPackageName of Object.keys(packageEntries)) {
292
- if (!packageNames.has(trackPackageName)) {
293
- continue;
294
- }
295
- trackedDependencies.add(trackPackageName);
296
- }
289
+ trackedDependencies.add(trackPackageName);
297
290
  }
298
291
  };
299
292
  var generateReverseGraph = (packages, packageGraph) => {
@@ -339,7 +332,8 @@ import { assertDefined as assertDefined6 } from "@package-pal/util";
339
332
 
340
333
  // packages/core/src/lib/graph/functions/dfs-traverse-graph-paths.ts
341
334
  import { assertDefined as assertDefined3 } from "@package-pal/util";
342
- var dfsTraverseGraphPaths = function* (graph, traverseFromPackages) {
335
+ var dfsTraverseGraphPaths = function* (graph, traverseFromPackages, options = {}) {
336
+ const { useGlobalVisited = true } = options;
343
337
  const globalVisited = new Set;
344
338
  const startPackages = Array.isArray(traverseFromPackages) ? traverseFromPackages : [traverseFromPackages];
345
339
  for (const start of startPackages) {
@@ -361,7 +355,7 @@ var dfsTraverseGraphPaths = function* (graph, traverseFromPackages) {
361
355
  }
362
356
  continue;
363
357
  }
364
- if (globalVisited.has(node)) {
358
+ if (useGlobalVisited && globalVisited.has(node)) {
365
359
  continue;
366
360
  }
367
361
  const newPath = [...path, node];
@@ -382,7 +376,9 @@ var dfsTraverseGraphPaths = function* (graph, traverseFromPackages) {
382
376
  if (!pushed) {
383
377
  yield newPath;
384
378
  }
385
- globalVisited.add(node);
379
+ if (useGlobalVisited) {
380
+ globalVisited.add(node);
381
+ }
386
382
  }
387
383
  }
388
384
  };
@@ -420,7 +416,12 @@ var extractSubgraph = (graph, fromPackages) => {
420
416
  const subgraph = new Map;
421
417
  for (const packageName of reachablePackages) {
422
418
  const node = assertDefined5(graph.get(packageName));
423
- const filteredNeighbours = new Set([...node.pointsToPackages].filter((dep) => reachablePackages.has(dep)));
419
+ const filteredNeighbours = new Set;
420
+ for (const dep of node.pointsToPackages) {
421
+ if (reachablePackages.has(dep)) {
422
+ filteredNeighbours.add(dep);
423
+ }
424
+ }
424
425
  subgraph.set(packageName, {
425
426
  packageData: node.packageData,
426
427
  pointsToPackages: filteredNeighbours
@@ -510,11 +511,14 @@ var getCircularDependencies = (inDegree) => {
510
511
  return Array.from(inDegree.keys()).sort((a, b) => {
511
512
  const degA = assertDefined7(inDegree.get(a));
512
513
  const degB = assertDefined7(inDegree.get(b));
513
- return degB - degA;
514
- }).sort();
514
+ if (degB !== degA) {
515
+ return degB - degA;
516
+ }
517
+ return a.localeCompare(b);
518
+ });
515
519
  };
516
520
  var generateTopologicalSortedGroups = (packageGraph, logger) => {
517
- logger.debug(styleText4("dim", "Generating topological sorted groups..."));
521
+ logger?.debug(styleText4("dim", "Generating topological sorted groups..."));
518
522
  const graphEntries = Array.from(packageGraph.entries());
519
523
  const inDegree = new Map(graphEntries.map(([packageName]) => [packageName, 0]));
520
524
  const graph = new Map(graphEntries.map(([packageName]) => [packageName, new Set]));
@@ -549,10 +553,10 @@ var generateTopologicalSortedGroups = (packageGraph, logger) => {
549
553
  }
550
554
  ready = nextReady;
551
555
  }
552
- logger.debug(styleText4("dim", `Sorted packages into ${result.length.toString()} sequential groups of parallelizable dependencies.`));
556
+ logger?.debug(styleText4("dim", `Sorted packages into ${result.length.toString()} sequential groups of parallelizable dependencies.`));
553
557
  const circular = getCircularDependencies(inDegree);
554
558
  if (circular.length) {
555
- logger.warn(styleText4("yellow", `${circular.length.toString()} packages could not be sorted due to circular dependencies. Correct ordering cannot be guaranteed.`));
559
+ logger?.warn(styleText4("yellow", `${circular.length.toString()} packages could not be sorted due to circular dependencies. Correct ordering cannot be guaranteed.`));
556
560
  }
557
561
  return {
558
562
  groups: result.map((group) => group.sort()),
@@ -561,104 +565,13 @@ var generateTopologicalSortedGroups = (packageGraph, logger) => {
561
565
  };
562
566
 
563
567
  // packages/core/src/lib/package/functions/load-packages.ts
564
- import { styleText as styleText6 } from "util";
565
-
566
- // packages/core/src/lib/package/functions/scan-packages.ts
567
568
  import { styleText as styleText5 } from "util";
568
- import {
569
- dirname as dirname5,
570
- join as join2
571
- } from "path";
572
- import { formatUnknownError } from "@package-pal/util";
573
-
574
- // packages/core/src/lib/package/functions/parse-package.ts
575
- import {
576
- dirname as dirname4,
577
- basename as basename2
578
- } from "path";
579
- import { isDefined as isDefined2 } from "@package-pal/util";
580
- var parsePackage = (path, text) => {
581
- const base = JSON.parse(text);
582
- if (!isDefined2(base) || typeof base !== "object") {
583
- return;
584
- }
585
- const props = base;
586
- const {
587
- dependencies,
588
- peerDependencies,
589
- devDependencies
590
- } = props;
591
- for (const field of Object.values(DependenciesField)) {
592
- const value = props[field];
593
- if (isDefined2(value) && typeof value !== "object") {
594
- return;
595
- }
596
- }
597
- return {
598
- rawContent: text,
599
- path,
600
- name: props.name ?? path,
601
- dir: basename2(dirname4(path)),
602
- version: props.version ?? undefined,
603
- dependencies: dependencies ?? undefined,
604
- peerDependencies: peerDependencies ?? undefined,
605
- devDependencies: devDependencies ?? undefined
606
- };
607
- };
608
-
609
- // packages/core/src/lib/package/functions/scan-glob-pattern-paths.ts
610
- import { mergeAsyncIters } from "@package-pal/util";
611
- var {Glob } = globalThis.Bun;
612
- var scanGlobPatternPaths = (patterns, options) => {
613
- return mergeAsyncIters(patterns.map((pattern) => new Glob(pattern).scan(options)));
614
- };
615
-
616
- // packages/core/src/lib/package/functions/scan-package-paths.ts
617
- var scanPackagePaths = (packages, cwd2) => {
618
- const baseOpts = {
619
- absolute: true,
620
- onlyFiles: false
621
- };
622
- const opts = {
623
- ...baseOpts,
624
- ...cwd2 ? { cwd: cwd2 } : {}
625
- };
626
- return scanGlobPatternPaths(packages, opts);
627
- };
628
-
629
- // packages/core/src/lib/package/functions/scan-packages.ts
630
- var scanPackages = async function* (patterns, logger, cwd2) {
631
- for await (const path of scanPackagePaths(patterns, cwd2)) {
632
- const packagePath = join2(path, "package.json");
633
- const dir = dirname5(packagePath);
634
- try {
635
- logger.debug(styleText5("dim", `Trying to read read package.json in '${dir}'.`));
636
- const file = Bun.file(packagePath);
637
- if (!file.size) {
638
- logger.debug(styleText5("dim", `Failed to read package.json in '${dir}' - ${styleText5("red", "File not found")}.`));
639
- continue;
640
- }
641
- const text = await file.text();
642
- const packageData = parsePackage(packagePath, text);
643
- if (!packageData) {
644
- logger.debug(styleText5("dim", `Invalid package.json found in '${dir}'.`));
645
- continue;
646
- }
647
- logger.debug(styleText5("dim", `Successfully read package.json in '${dir}'.`));
648
- yield packageData;
649
- } catch (e) {
650
- logger.debug(styleText5("dim", `Failed to read package.json in '${dir}' - ${styleText5("red", formatUnknownError(e))}.`));
651
- }
652
- }
653
- };
654
-
655
- // packages/core/src/lib/package/functions/load-packages.ts
656
- var loadPackages = async (rootDir, packagePatterns, logger) => {
569
+ var loadPackages = async (rootDir, packagePatterns, adapter, logger) => {
657
570
  const patternContent = packagePatterns.map((pattern) => `'${pattern}'`).join(", ");
658
- logger.debug(styleText6("dim", `Loading packages matching pattern/s ${patternContent}...${rootDir ? ` from ${rootDir}` : ""}`));
571
+ logger.debug(styleText5("dim", `Loading packages matching pattern/s ${patternContent}...${rootDir ? ` from ${rootDir}` : ""}`));
659
572
  const packages = [];
660
573
  const seen = new Set;
661
- for await (const packageData of scanPackages(Array.from(new Set(packagePatterns)), logger, rootDir)) {
574
+ for await (const packageData of adapter.scanPackages(Array.from(new Set(packagePatterns)), logger, rootDir)) {
662
575
  if (seen.has(packageData.name)) {
663
576
  continue;
664
577
  }
@@ -672,14 +585,14 @@ var loadPackages = async (rootDir, packagePatterns, logger) => {
672
585
  };
673
586
 
674
587
  // packages/core/src/lib/package/functions/run-for-each-package.ts
675
- import { dirname as dirname6 } from "path";
588
+ import { dirname as dirname4 } from "path";
676
589
  import {
677
- assertDefined as assertDefined9,
590
+ assertDefined as assertDefined8,
678
591
  runAsync
679
592
  } from "@package-pal/util";
680
593
 
681
594
  // packages/core/src/lib/process/functions/run-subprocess.ts
682
- import { styleText as styleText7 } from "util";
595
+ import { styleText as styleText6 } from "util";
683
596
 
684
597
  // packages/core/src/lib/process/types/exit-state.ts
685
598
  var ExitState = {
@@ -694,12 +607,95 @@ var StdType = {
694
607
  Err: "Err"
695
608
  };
696
609
 
610
+ // packages/core/src/lib/process/functions/get-commands-for-shell.ts
611
+ import { identity } from "@package-pal/util";
612
+
613
+ // packages/core/src/lib/types/shell.ts
614
+ var Shell = {
615
+ sh: "sh",
616
+ bash: "bash",
617
+ zsh: "zsh",
618
+ pwsh: "pwsh",
619
+ fish: "fish",
620
+ powershell: "powershell",
621
+ cmd: "cmd"
622
+ };
623
+
624
+ // packages/core/src/lib/process/functions/get-shell.ts
625
+ import { userInfo } from "os";
626
+ import { basename as basename2 } from "path";
627
+ import {
628
+ platform,
629
+ env
630
+ } from "process";
631
+ var cachedShell = null;
632
+ var cacheShell = (shell) => {
633
+ cachedShell = shell;
634
+ return shell;
635
+ };
636
+ var mapShell = (shellPath) => {
637
+ if (!shellPath) {
638
+ return Shell.sh;
639
+ }
640
+ const name = basename2(shellPath).replace(/\.exe$/i, "").toLowerCase();
641
+ switch (name) {
642
+ case "bash":
643
+ return Shell.bash;
644
+ case "zsh":
645
+ return Shell.zsh;
646
+ case "fish":
647
+ return Shell.fish;
648
+ case "sh":
649
+ return Shell.sh;
650
+ default:
651
+ return Shell.sh;
652
+ }
653
+ };
654
+ var getShell = () => {
655
+ if (cachedShell !== null) {
656
+ return cachedShell;
657
+ }
658
+ if (env.ZSH_VERSION) {
659
+ return cacheShell(Shell.zsh);
660
+ }
661
+ if (env.BASH_VERSION) {
662
+ return cacheShell(Shell.bash);
663
+ }
664
+ if (env.FISH_VERSION) {
665
+ return cacheShell(Shell.fish);
666
+ }
667
+ const isWindows = platform === "win32";
668
+ if (isWindows) {
669
+ if ((env.MSYSTEM || env.MINGW_PREFIX) && Bun.which(Shell.bash)) {
670
+ return cacheShell(Shell.bash);
671
+ }
672
+ if (Bun.which(Shell.pwsh)) {
673
+ return cacheShell(Shell.pwsh);
674
+ }
675
+ if (Bun.which(Shell.powershell)) {
676
+ return cacheShell(Shell.powershell);
677
+ }
678
+ return cacheShell(Shell.cmd);
679
+ }
680
+ if (env.SHELL) {
681
+ return cacheShell(mapShell(env.SHELL));
682
+ }
683
+ try {
684
+ const userShell = userInfo().shell;
685
+ if (userShell) {
686
+ return cacheShell(mapShell(userShell));
687
+ }
688
+ } catch {}
689
+ return cacheShell(Shell.sh);
690
+ };
691
+
697
692
  // packages/core/src/lib/process/functions/parse-ps-shell-flags.ts
698
- import { assertDefined as assertDefined8 } from "@package-pal/util";
699
693
  var shellFlagsWithParams = new Set([
700
694
  "-executionpolicy",
701
695
  "-windowstyle",
702
- "-version"
696
+ "-version",
697
+ "-encodedcommand",
698
+ "-command"
703
699
  ]);
704
700
  var shellFlagsNoParams = new Set([
705
701
  "-noprofile",
@@ -713,92 +709,68 @@ var shellFlagsNoParams = new Set([
713
709
  "-usewindowspowerShell"
714
710
  ]);
715
711
  var parsePsShellFlags = (input) => {
716
- const isPreEncoded = input.toLowerCase().includes("-encodedcommand");
717
- const tokens = input.match(/"[^"]*"|'[^']*'|\S+/g) ?? [];
718
712
  const flags = new Set;
719
- let i = 0;
720
- while (i < tokens.length) {
721
- const token = assertDefined8(tokens[i]);
713
+ const tokenRegex = /("[^"]*"|'[^']*'|\S+)/g;
714
+ let match;
715
+ while ((match = tokenRegex.exec(input)) !== null) {
716
+ const token = match[0];
722
717
  const tokenLower = token.toLowerCase();
723
718
  if (shellFlagsWithParams.has(tokenLower)) {
724
719
  flags.add(token);
725
- if (i + 1 < tokens.length) {
726
- flags.add(assertDefined8(tokens[i + 1]));
727
- i++;
720
+ const nextMatch = tokenRegex.exec(input);
721
+ if (nextMatch) {
722
+ flags.add(nextMatch[0]);
728
723
  }
729
- i++;
730
724
  } else if (shellFlagsNoParams.has(tokenLower)) {
731
725
  flags.add(token);
732
- i++;
733
726
  } else {
734
- break;
727
+ const isPreEncoded2 = Array.from(flags).some((flag) => flag.toLowerCase() === "-encodedcommand");
728
+ return {
729
+ flags,
730
+ command: input.slice(match.index),
731
+ isPreEncoded: isPreEncoded2
732
+ };
735
733
  }
736
734
  }
737
- const command = tokens.slice(i).join(" ");
735
+ const isPreEncoded = Array.from(flags).some((flag) => flag.toLowerCase() === "-encodedcommand");
738
736
  return {
739
737
  flags,
740
- command,
738
+ command: "",
741
739
  isPreEncoded
742
740
  };
743
741
  };
744
742
 
745
- // packages/core/src/lib/types/shell.ts
746
- var Shell = {
747
- sh: "sh",
748
- bash: "bash",
749
- zsh: "zsh",
750
- pwsh: "pwsh",
751
- fish: "fish",
752
- powershell: "powershell",
753
- cmd: "cmd"
754
- };
755
-
756
- // packages/core/src/lib/process/functions/escape-shell-arg.ts
757
- var escapeShellArg = (value, shell) => {
758
- switch (shell) {
759
- case Shell.cmd: {
760
- const escaped = value.replace(/\^/g, "^^^^").replace(/([&<>|()])/g, "^$1").replace(/!/g, "^^!").replace(/%/g, "%%%%");
761
- return `"${escaped}"`;
743
+ // packages/core/src/lib/process/functions/strip-clixml.ts
744
+ var createClixmlStripper = () => {
745
+ let buffer = "";
746
+ return (chunk) => {
747
+ buffer += chunk;
748
+ if (!buffer.includes("<") && !buffer.includes("#< CLIXML")) {
749
+ const out = buffer;
750
+ buffer = "";
751
+ return out;
762
752
  }
763
- case Shell.powershell:
764
- case Shell.pwsh:
765
- return `'${value.replace(/'/g, "''")}'`;
766
- case Shell.sh:
767
- case Shell.bash:
768
- case Shell.zsh:
769
- case Shell.fish:
770
- default:
771
- return `'${value.replace(/'/g, "'\\''")}'`;
772
- }
773
- };
774
-
775
- // packages/core/src/lib/process/functions/get-shell.ts
776
- import {
777
- platform,
778
- env
779
- } from "process";
780
- var getShell = () => {
781
- const isWindows = platform === "win32";
782
- if (!isWindows) {
783
- const envShell = (env.SHELL ?? "").toLowerCase();
784
- switch (true) {
785
- case envShell.includes("bash"):
786
- return Shell.bash;
787
- case envShell.includes("zsh"):
788
- return Shell.zsh;
789
- case envShell.includes("fish"):
790
- return Shell.fish;
791
- default:
792
- return Shell.sh;
753
+ const hasClixmlHeader = buffer.includes("#< CLIXML");
754
+ const hasClixmlTags = /<Obj|S S="Error"|<\/Objs>/.test(buffer);
755
+ if (!hasClixmlHeader && !hasClixmlTags) {
756
+ const out = buffer;
757
+ buffer = "";
758
+ return out;
793
759
  }
794
- }
795
- if (Bun.which(Shell.pwsh)) {
796
- return Shell.pwsh;
797
- }
798
- if (Bun.which(Shell.powershell)) {
799
- return Shell.powershell;
800
- }
801
- return Shell.cmd;
760
+ buffer = buffer.replace(/#< CLIXML/g, "").replace(/<Obj S="progress"[\s\S]*?<\/Obj>/g, "");
761
+ let output = "";
762
+ buffer = buffer.replace(/<S S="Error">([\s\S]*?)<\/S>/g, (_, msg) => {
763
+ output += msg;
764
+ return "";
765
+ });
766
+ if (buffer.includes("</Objs>")) {
767
+ output += buffer.replace(/<[^>]+>/g, "");
768
+ buffer = "";
769
+ }
770
+ if (!output)
771
+ return "";
772
+ return output.replace(/_x([0-9A-F]{4})_/g, (_, hex) => String.fromCharCode(parseInt(hex, 16))).replace(/<[^>]+>/g, "");
773
+ };
802
774
  };
803
775
 
804
776
  // packages/core/src/lib/process/functions/get-commands-for-shell.ts
@@ -806,11 +778,14 @@ var getCommandsForShell = (shellCommand) => {
806
778
  const shell = getShell();
807
779
  switch (shell) {
808
780
  case Shell.cmd:
809
- return [
810
- shell,
811
- "/c",
812
- escapeShellArg(shellCommand, shell)
813
- ];
781
+ return {
782
+ commands: [
783
+ shell,
784
+ "/c",
785
+ shellCommand
786
+ ],
787
+ stderrProcessor: identity
788
+ };
814
789
  case Shell.pwsh:
815
790
  case Shell.powershell:
816
791
  const {
@@ -819,35 +794,66 @@ var getCommandsForShell = (shellCommand) => {
819
794
  isPreEncoded
820
795
  } = parsePsShellFlags(shellCommand);
821
796
  if (isPreEncoded) {
822
- return [shell, shellCommand];
797
+ return {
798
+ commands: [shell, ...flags],
799
+ stderrProcessor: createClixmlStripper()
800
+ };
823
801
  }
824
802
  const encodedCommand = Buffer.from(command || " ", "utf16le").toString("base64");
825
- return [
826
- shell,
827
- ...flags,
828
- ...encodedCommand ? ["-EncodedCommand", encodedCommand] : []
829
- ];
803
+ return {
804
+ commands: [
805
+ shell,
806
+ ...flags,
807
+ ...encodedCommand ? ["-EncodedCommand", encodedCommand] : []
808
+ ],
809
+ stderrProcessor: createClixmlStripper()
810
+ };
830
811
  default:
831
- return [
832
- shell,
833
- "-c",
834
- escapeShellArg(shellCommand, shell)
835
- ];
812
+ return {
813
+ commands: [
814
+ shell,
815
+ "-c",
816
+ shellCommand
817
+ ],
818
+ stderrProcessor: identity
819
+ };
836
820
  }
837
821
  };
838
822
 
839
823
  // packages/core/src/lib/process/functions/get-line-buffered-writer.ts
840
- import { identity } from "@package-pal/util";
841
- var getLineBufferedWriter = (prefix, style = identity, write = process.stdout.write.bind(process.stdout)) => {
824
+ import { identity as identity2 } from "@package-pal/util";
825
+ var getLineBufferedWriter = (prefix, style = identity2, write = process.stdout.write.bind(process.stdout)) => {
842
826
  let buffer = "";
843
- return (chunk) => {
844
- buffer += chunk;
845
- const lines = buffer.split(`
827
+ return {
828
+ write: (chunk) => {
829
+ if (chunk === null) {
830
+ if (buffer.length > 0) {
831
+ write(`${prefix}${style(buffer)}
846
832
  `);
847
- buffer = lines.pop() ?? "";
848
- for (const line of lines) {
849
- write(`${prefix}${style(line)}
833
+ buffer = "";
834
+ }
835
+ return;
836
+ }
837
+ buffer += chunk;
838
+ let start = 0;
839
+ let newlineIndex = buffer.indexOf(`
850
840
  `);
841
+ while (newlineIndex !== -1) {
842
+ let end = newlineIndex;
843
+ if (end > start && buffer[end - 1] === "\r") {
844
+ end--;
845
+ }
846
+ const line = buffer.slice(start, end);
847
+ write(`${prefix}${style(line)}
848
+ `);
849
+ start = newlineIndex + 1;
850
+ newlineIndex = buffer.indexOf(`
851
+ `, start);
852
+ }
853
+ buffer = buffer.slice(start);
854
+ },
855
+ flush() {
856
+ this.write(null);
851
857
  }
852
858
  };
853
859
  };
@@ -856,10 +862,14 @@ var getLineBufferedWriter = (prefix, style = identity, write = process.stdout.wr
856
862
  var readStream = async (stream, use) => {
857
863
  const decoder = new TextDecoder;
858
864
  const reader = stream.getReader();
859
- let result = await reader.read();
860
- while (!result.done) {
861
- use(decoder.decode(result.value, { stream: true }));
862
- result = await reader.read();
865
+ try {
866
+ let result = await reader.read();
867
+ while (!result.done) {
868
+ use(decoder.decode(result.value, { stream: true }));
869
+ result = await reader.read();
870
+ }
871
+ } finally {
872
+ reader.releaseLock();
863
873
  }
864
874
  const flush = decoder.decode();
865
875
  if (flush) {
@@ -878,14 +888,21 @@ var cancelCodes = new Set([
878
888
  ]);
879
889
  var runSubprocess = async (opts) => {
880
890
  if (opts.signal?.aborted) {
881
- opts.logger.debug(styleText7("dim", `Skipped '${opts.debugName}' subprocess command; signal already cancelled.`));
891
+ opts.logger?.debug(styleText6("dim", `Skipped '${opts.debugName}' subprocess command; signal already cancelled.`));
882
892
  return ExitState.Cancelled;
883
893
  }
884
- const commands = getCommandsForShell(opts.shellCommand);
894
+ const {
895
+ commands,
896
+ stderrProcessor
897
+ } = getCommandsForShell(opts.shellCommand);
885
898
  const baseSubprocessOpts = {
886
899
  stdout: "pipe",
887
900
  stderr: "pipe",
888
- stdin: "ignore"
901
+ stdin: "ignore",
902
+ env: {
903
+ ...process.env,
904
+ ...opts.env
905
+ }
889
906
  };
890
907
  const subprocessOpts = {
891
908
  ...baseSubprocessOpts,
@@ -898,25 +915,30 @@ var runSubprocess = async (opts) => {
898
915
  const [readStdout, readStderr] = [{
899
916
  source: subprocess.stdout,
900
917
  type: StdType.Out,
901
- write: getLineBufferedWriter(styleText7("dim", `[O-${pid}]`.padEnd(minPrefixLen, " ")))
918
+ writer: getLineBufferedWriter(styleText6("dim", `[O-${pid}]`.padEnd(minPrefixLen, " ")))
902
919
  }, {
903
920
  source: subprocess.stderr,
904
921
  type: StdType.Err,
905
- write: getLineBufferedWriter(styleText7("yellow", styleText7("dim", `[E-${pid}]`.padEnd(minPrefixLen, " "))))
906
- }].map(({
922
+ writer: getLineBufferedWriter(styleText6("yellow", styleText6("dim", `[E-${pid}]`.padEnd(minPrefixLen, " "))), undefined, process.stderr.write.bind(process.stderr))
923
+ }].map(async ({
907
924
  source,
908
925
  type,
909
- write
926
+ writer
910
927
  }) => {
911
- return readStream(source, (chunk) => {
912
- write(chunk);
928
+ await readStream(source, (chunk) => {
929
+ const processedChunk = type === StdType.Err ? stderrProcessor(chunk) : chunk;
930
+ if (processedChunk === "" && chunk !== "") {
931
+ return;
932
+ }
933
+ writer.write(processedChunk);
913
934
  if (opts.onStdChunk) {
914
- opts.onStdChunk(chunk, type);
935
+ opts.onStdChunk(processedChunk, type);
915
936
  }
916
937
  });
938
+ writer.flush();
917
939
  });
918
940
  const executedCommand = commands.join(" ");
919
- opts.logger.debug(styleText7("dim", `Started '${opts.debugName}' subprocess command '${opts.shellCommand}' (${executedCommand}) with PID ${pid}.`));
941
+ opts.logger?.debug(styleText6("dim", `Started '${opts.debugName}' subprocess command '${opts.shellCommand}' (${executedCommand}) with PID ${pid}.`));
920
942
  const [
921
943
  ,
922
944
  ,
@@ -926,14 +948,14 @@ var runSubprocess = async (opts) => {
926
948
  readStderr,
927
949
  subprocess.exited.then((exitCode) => {
928
950
  if (cancelCodes.has(exitCode)) {
929
- opts.logger.debug(styleText7("dim", `Cancelled '${opts.debugName}' subprocess command; PID ${pid} exited.`));
951
+ opts.logger?.debug(styleText6("dim", `Cancelled '${opts.debugName}' subprocess command; PID ${pid} exited.`));
930
952
  return ExitState.Cancelled;
931
953
  }
932
954
  if (exitCode !== 0) {
933
- opts.logger.error(styleText7("red", `'${opts.debugName}' command '${opts.shellCommand}' (${executedCommand}) with PID ${pid} failed with exit code ${exitCode.toString()}.`));
955
+ opts.logger?.error(styleText6("red", `'${opts.debugName}' command '${opts.shellCommand}' (${executedCommand}) with PID ${pid} failed with exit code ${exitCode.toString()}.`));
934
956
  return ExitState.Errored;
935
957
  }
936
- opts.logger.debug(styleText7("dim", `Completed '${opts.debugName}' subprocess command; PID ${pid} exited.`));
958
+ opts.logger?.debug(styleText6("dim", `Completed '${opts.debugName}' subprocess command; PID ${pid} exited.`));
937
959
  return ExitState.Completed;
938
960
  })
939
961
  ]);
@@ -943,18 +965,18 @@ var runSubprocess = async (opts) => {
943
965
  // packages/core/src/lib/package/functions/run-for-each-package.ts
944
966
  var runForEachPackage = async (packageGraphs, packageOrder, getCommand, logger, topological = true, concurrency) => {
945
967
  const controller = new AbortController;
946
- let processPackageOrder = packageOrder.groups.concat(packageOrder.circular);
968
+ let processPackageOrder = packageOrder.circular.length > 0 ? packageOrder.groups.concat([packageOrder.circular]) : packageOrder.groups;
947
969
  if (!topological) {
948
970
  processPackageOrder = [processPackageOrder.flat()];
949
971
  }
950
972
  for (const group of processPackageOrder) {
951
973
  await runAsync(group.map((packageName) => async () => {
952
- const packageNode = assertDefined9(packageGraphs.dependencies.get(packageName));
974
+ const packageNode = assertDefined8(packageGraphs.dependencies.get(packageName));
953
975
  const processPackageProps = {
954
976
  name: packageName,
955
977
  dir: packageNode.packageData.dir
956
978
  };
957
- const processPackageCwd = dirname6(packageNode.packageData.path);
979
+ const processPackageCwd = dirname4(packageNode.packageData.path);
958
980
  const shellCommand = await getCommand(processPackageProps);
959
981
  if (!shellCommand) {
960
982
  return;
@@ -963,6 +985,10 @@ var runForEachPackage = async (packageGraphs, packageOrder, getCommand, logger,
963
985
  debugName: `run for ${packageName}`,
964
986
  shellCommand,
965
987
  cwd: processPackageCwd,
988
+ env: {
989
+ PP_PACKAGE_NAME: packageName,
990
+ PP_PACKAGE_DIR: processPackageProps.dir
991
+ },
966
992
  signal: controller.signal,
967
993
  logger
968
994
  });
@@ -974,139 +1000,24 @@ var runForEachPackage = async (packageGraphs, packageOrder, getCommand, logger,
974
1000
  }
975
1001
  };
976
1002
 
977
- // packages/core/src/lib/package/functions/update-package-version.ts
978
- import { styleText as styleText8 } from "util";
979
- var {semver } = globalThis.Bun;
980
- import { inc } from "semver";
981
- var findAndReplaceVersion = ({
982
- raw,
983
- field,
984
- packageName,
985
- updatePackageName,
986
- newVersion,
987
- exact,
988
- logger
989
- }) => {
990
- if (field === "version" && packageName === updatePackageName) {
991
- const versionKey = `"version"`;
992
- const keyIndex = raw.indexOf(versionKey);
993
- if (keyIndex === -1) {
994
- return raw;
995
- }
996
- const versionStart2 = raw.indexOf('"', keyIndex + versionKey.length);
997
- const versionEnd2 = raw.indexOf('"', versionStart2 + 1);
998
- if (versionStart2 === -1 || versionEnd2 === -1) {
999
- return raw;
1000
- }
1001
- const currentVersionString2 = raw.slice(versionStart2 + 1, versionEnd2);
1002
- const updatedVersion2 = newVersion;
1003
- logger.info(`Updating '${updatePackageName}' version: ${currentVersionString2} \u2192 ${updatedVersion2}.`);
1004
- const before2 = raw.slice(0, versionStart2 + 1);
1005
- const after2 = raw.slice(versionEnd2);
1006
- return `${before2}${updatedVersion2}${after2}`;
1007
- }
1008
- const fieldIndex = raw.indexOf(`"${field}"`);
1009
- if (fieldIndex === -1) {
1010
- return raw;
1011
- }
1012
- const fieldStart = raw.indexOf("{", fieldIndex);
1013
- if (fieldStart === -1) {
1014
- return raw;
1015
- }
1016
- const fieldEnd = raw.indexOf("}", fieldStart);
1017
- if (fieldEnd === -1) {
1018
- return raw;
1019
- }
1020
- const fieldBlock = raw.slice(fieldStart, fieldEnd);
1021
- const depKey = `"${packageName}"`;
1022
- const depIndex = fieldBlock.indexOf(depKey);
1023
- if (depIndex === -1) {
1024
- return raw;
1025
- }
1026
- const versionStart = fieldBlock.indexOf('"', depIndex + depKey.length);
1027
- const versionEnd = fieldBlock.indexOf('"', versionStart + 1);
1028
- if (versionStart === -1 || versionEnd === -1) {
1029
- return raw;
1030
- }
1031
- const currentVersionString = fieldBlock.slice(versionStart + 1, versionEnd);
1032
- const preservedPrefix = exact ? "" : /^([~^><=]*)/.exec(currentVersionString)?.[1] ?? "";
1033
- const updatedVersion = `${preservedPrefix}${newVersion}`;
1034
- logger.info(`Updating '${updatePackageName}' ${field} '${packageName}': ${currentVersionString} \u2192 ${updatedVersion}.`);
1035
- const before = raw.slice(0, fieldStart + versionStart + 1);
1036
- const after = raw.slice(fieldStart + versionEnd);
1037
- return `${before}${updatedVersion}${after}`;
1038
- };
1039
- var updatePackageVersion = async (packageName, type, packageGraphs, preId, exact, logger) => {
1040
- logger.debug(styleText8("dim", `Bumping package '${packageName}'...`));
1041
- const packageNode = packageGraphs.dependencies.get(packageName);
1042
- if (!packageNode) {
1043
- throw new Error(`Package '${packageName}' not found.`);
1044
- }
1045
- const currentVersion = packageNode.packageData.version;
1046
- if (!currentVersion) {
1047
- throw new Error(`Package '${packageName}' has no version.`);
1048
- }
1049
- const bumpedVersion = inc(currentVersion, type, undefined, preId);
1050
- if (!bumpedVersion) {
1051
- throw new Error(`Package '${packageName}' version '${currentVersion}' is invalid.`);
1052
- }
1053
- const updatedContent = findAndReplaceVersion({
1054
- raw: packageNode.packageData.rawContent,
1055
- field: "version",
1056
- packageName,
1057
- updatePackageName: packageName,
1058
- newVersion: bumpedVersion,
1059
- exact,
1060
- logger
1061
- });
1062
- const baseWrite = Bun.write(packageNode.packageData.path, updatedContent);
1063
- const dependentWrites = Array.from(dfsTraverseGraph(packageGraphs.dependents, packageName).flatMap((dependent) => {
1064
- return Object.values(DependenciesField).flatMap((field) => {
1065
- const entry = dependent[field];
1066
- const depVersion = entry?.[packageName];
1067
- if (!depVersion) {
1068
- return [];
1069
- }
1070
- if (exact ? depVersion === bumpedVersion : semver.satisfies(bumpedVersion, depVersion)) {
1071
- logger.debug(styleText8("dim", `Skipping '${dependent.name}': ${field} version '${depVersion}' already satisfies '${bumpedVersion}'.`));
1072
- return [];
1073
- }
1074
- const updatedContent2 = findAndReplaceVersion({
1075
- raw: dependent.rawContent,
1076
- field,
1077
- packageName,
1078
- updatePackageName: dependent.name,
1079
- newVersion: bumpedVersion,
1080
- exact,
1081
- logger
1082
- });
1083
- return [Bun.write(dependent.path, updatedContent2)];
1084
- });
1085
- }));
1086
- return Promise.all([baseWrite, ...dependentWrites]).then(() => {
1087
- return;
1088
- });
1089
- };
1090
-
1091
1003
  // packages/core/src/lib/watch/functions/watch-package-changes.ts
1092
1004
  import {
1093
1005
  watch
1094
1006
  } from "fs";
1095
- import { styleText as styleText10 } from "util";
1096
1007
  import {
1097
- dirname as dirname8,
1098
- join as join4
1008
+ dirname as dirname6,
1009
+ join as join3
1099
1010
  } from "path";
1011
+ import { styleText as styleText8 } from "util";
1100
1012
  import {
1101
1013
  assertDefined as assertDefined12,
1102
- DedupePathsBy,
1103
- dedupeSharedPaths,
1104
1014
  getDeferredPromise,
1105
1015
  getStringMatcher,
1106
- isDefined as isDefined4,
1016
+ isDefined as isDefined3,
1017
+ normalisePath,
1107
1018
  runAsync as runAsync2
1108
1019
  } from "@package-pal/util";
1109
- var {Glob: Glob2 } = globalThis.Bun;
1020
+ var {Glob } = globalThis.Bun;
1110
1021
 
1111
1022
  // packages/core/src/lib/graph/functions/merge-graphs.ts
1112
1023
  var mergeGraphs = (a, b) => {
@@ -1133,28 +1044,67 @@ var ChangeAction = {
1133
1044
  Restart: "Restart"
1134
1045
  };
1135
1046
 
1047
+ // packages/core/src/lib/watch/types/dedupe-paths-by.ts
1048
+ var DedupePathsBy = {
1049
+ Parent: "parent",
1050
+ Child: "child"
1051
+ };
1052
+
1053
+ // packages/core/src/lib/watch/functions/dedupe-shared-paths.ts
1054
+ import { sep } from "path";
1055
+ import { assertDefined as assertDefined9 } from "@package-pal/util";
1056
+ var dedupeSharedPaths = (paths, by) => {
1057
+ const sorted = paths.toSorted((a, b) => a.split(sep).length - b.split(sep).length);
1058
+ const deduped = [];
1059
+ if (by === DedupePathsBy.Parent) {
1060
+ for (const path of sorted) {
1061
+ if (!deduped.some((base) => path.startsWith(base + sep))) {
1062
+ deduped.push(path);
1063
+ }
1064
+ }
1065
+ return deduped;
1066
+ }
1067
+ for (const path of sorted) {
1068
+ for (let i = deduped.length - 1;i >= 0; i--) {
1069
+ const base = assertDefined9(deduped[i]);
1070
+ if (path.startsWith(base + sep)) {
1071
+ deduped.splice(i, 1);
1072
+ }
1073
+ }
1074
+ if (!deduped.some((base) => base.startsWith(path + sep))) {
1075
+ deduped.push(path);
1076
+ }
1077
+ }
1078
+ return Array.from(new Set(deduped));
1079
+ };
1080
+
1136
1081
  // packages/core/src/lib/watch/functions/filter-files-modified-since.ts
1137
- var filterFilesModifiedSince = (paths, sinceMs) => {
1138
- return paths.filter((path) => {
1139
- const changedFile = Bun.file(path);
1140
- const isDeleted = changedFile.lastModified === 0;
1141
- const isModifiedSince = changedFile.lastModified >= sinceMs;
1142
- return isDeleted || isModifiedSince;
1143
- });
1082
+ import { stat } from "fs/promises";
1083
+ var filterFilesModifiedSince = async (paths, sinceMs) => {
1084
+ const results = await Promise.all(paths.map(async (path) => {
1085
+ try {
1086
+ const s = await stat(path);
1087
+ const isModifiedSince = s.mtimeMs >= sinceMs;
1088
+ return isModifiedSince ? path : null;
1089
+ } catch {
1090
+ return path;
1091
+ }
1092
+ }));
1093
+ return results.filter((path) => path !== null);
1144
1094
  };
1145
1095
 
1146
1096
  // packages/core/src/lib/watch/functions/get-change-logic.ts
1147
- import { styleText as styleText9 } from "util";
1097
+ import { styleText as styleText7 } from "util";
1148
1098
  import { assertDefined as assertDefined11 } from "@package-pal/util";
1149
1099
 
1150
1100
  // packages/core/src/lib/graph/functions/generate-topological-ranking-range.ts
1151
- import { isDefined as isDefined3 } from "@package-pal/util";
1101
+ import { isDefined as isDefined2 } from "@package-pal/util";
1152
1102
  var generateTopologicalRankingRange = (graph, ranking) => {
1153
1103
  let min = Infinity;
1154
1104
  let max = -Infinity;
1155
1105
  for (const key of graph.keys()) {
1156
1106
  const rank = ranking.get(key);
1157
- if (!isDefined3(rank)) {
1107
+ if (!isDefined2(rank)) {
1158
1108
  continue;
1159
1109
  }
1160
1110
  if (rank < min) {
@@ -1245,21 +1195,21 @@ var getChangeLogic = (packageGraphs, packageChanges, lastProcessedSubgraph, conf
1245
1195
  const changedPackages = Array.from(packageChanges.keys());
1246
1196
  const changedFilePaths = Array.from(packageChanges.values()).flat();
1247
1197
  if (packageChanges.size) {
1248
- logger.debug(styleText9("dim", `Changes detected in ${changedPackages.map((packageName) => `'${packageName}'`).join(", ")}.`));
1249
- logger.debug(styleText9("dim", `Changed file paths: ${changedFilePaths.map((filePath) => `'${filePath}'`).join(", ")}.`));
1198
+ logger?.debug(styleText7("dim", `Changes detected in ${changedPackages.map((packageName) => `'${packageName}'`).join(", ")}.`));
1199
+ logger?.debug(styleText7("dim", `Changed file paths: ${changedFilePaths.map((filePath) => `'${filePath}'`).join(", ")}.`));
1250
1200
  }
1251
1201
  const packageOrder = generateTopologicalSortedGroups(packageGraphs.dependents, logger);
1252
- const packageProcessOrder = packageOrder.groups.toReversed().concat(packageOrder.circular);
1202
+ const packageProcessOrder = packageOrder.circular.length > 0 ? packageOrder.groups.toReversed().concat([packageOrder.circular]) : packageOrder.groups.toReversed();
1253
1203
  const packageRankings = generateTopologicalRanking(packageProcessOrder);
1254
1204
  const changedPackageSubgraph = extractSubgraph(packageGraphs.dependents, changedPackages);
1255
1205
  const changedPackageOrder = generateTopologicalSortedGroups(changedPackageSubgraph, logger);
1256
- const changedPackageProcessOrder = changedPackageOrder.groups.toReversed().concat(changedPackageOrder.circular);
1206
+ const changedPackageProcessOrder = changedPackageOrder.circular.length > 0 ? changedPackageOrder.groups.toReversed().concat([changedPackageOrder.circular]) : changedPackageOrder.groups.toReversed();
1257
1207
  const isSubgraphOfPrevious = !!lastProcessedSubgraph && isSubgraph(lastProcessedSubgraph, changedPackageSubgraph);
1258
1208
  const isDisjointFromPrevious = !lastProcessedSubgraph || !isSubgraphOfPrevious && isDisjoint(lastProcessedSubgraph, changedPackageSubgraph);
1259
1209
  const isRankedGreaterThanOrEqualToPrevious = !!lastProcessedSubgraph && !isSubgraphOfPrevious && isRankedGreaterThanOrEqual(lastProcessedSubgraph, changedPackageSubgraph, packageRankings);
1260
- logger.debug(styleText9("dim", `Changes are subgraph of previous: ${isSubgraphOfPrevious.toString()}.`));
1261
- logger.debug(styleText9("dim", `Changes are disjoint from previous: ${isDisjointFromPrevious.toString()}.`));
1262
- logger.debug(styleText9("dim", `Changes are ranked greater than or equal to previous: ${isRankedGreaterThanOrEqualToPrevious.toString()}.`));
1210
+ logger?.debug(styleText7("dim", `Changes are subgraph of previous: ${isSubgraphOfPrevious.toString()}.`));
1211
+ logger?.debug(styleText7("dim", `Changes are disjoint from previous: ${isDisjointFromPrevious.toString()}.`));
1212
+ logger?.debug(styleText7("dim", `Changes are ranked greater than or equal to previous: ${isRankedGreaterThanOrEqualToPrevious.toString()}.`));
1263
1213
  let action = ChangeAction.Restart;
1264
1214
  if (!packageChanges.size) {
1265
1215
  action = ChangeAction.Ignore;
@@ -1279,7 +1229,7 @@ var getChangeLogic = (packageGraphs, packageChanges, lastProcessedSubgraph, conf
1279
1229
  });
1280
1230
  }
1281
1231
  }
1282
- logger.debug(styleText9("dim", `Determined change action: ${action}.`));
1232
+ logger?.debug(styleText7("dim", `Determined change action: ${action}.`));
1283
1233
  return {
1284
1234
  changedPackageProcessOrder,
1285
1235
  changedPackageSubgraph,
@@ -1287,16 +1237,11 @@ var getChangeLogic = (packageGraphs, packageChanges, lastProcessedSubgraph, conf
1287
1237
  };
1288
1238
  };
1289
1239
 
1290
- // packages/core/src/lib/watch/functions/normalise-pattern-separators.ts
1291
- var normalisePatternSeparators = (path) => {
1292
- return path.replace(/\\/g, "/");
1293
- };
1294
-
1295
1240
  // packages/core/src/lib/watch/functions/normalise-watched-file-path.ts
1296
1241
  import {
1297
1242
  basename as basename3,
1298
- dirname as dirname7,
1299
- join as join3
1243
+ dirname as dirname5,
1244
+ join as join2
1300
1245
  } from "path";
1301
1246
  var removeTrailing = [
1302
1247
  "~",
@@ -1309,7 +1254,7 @@ var removeTrailing = [
1309
1254
  ".swn"
1310
1255
  ];
1311
1256
  var normaliseWatchedFilePath = (filePath) => {
1312
- const dir = dirname7(filePath);
1257
+ const dir = dirname5(filePath);
1313
1258
  let base = basename3(filePath);
1314
1259
  for (const trailing of removeTrailing) {
1315
1260
  if (base.toLowerCase().endsWith(trailing)) {
@@ -1318,33 +1263,32 @@ var normaliseWatchedFilePath = (filePath) => {
1318
1263
  break;
1319
1264
  }
1320
1265
  }
1321
- return join3(dir, base);
1266
+ return join2(dir, base);
1322
1267
  };
1323
1268
 
1324
1269
  // packages/core/src/lib/watch/functions/watch-package-changes.ts
1325
1270
  var fileModifiedThresholdMs = 5000;
1326
- var lastProcessedSubgraph;
1327
- var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determineAbortController, logger) => {
1271
+ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determineAbortController, state, logger) => {
1328
1272
  const {
1329
1273
  action,
1330
1274
  changedPackageProcessOrder,
1331
1275
  changedPackageSubgraph
1332
- } = getChangeLogic(packageGraphs, packageChanges, lastProcessedSubgraph, watchConfig, logger);
1276
+ } = getChangeLogic(packageGraphs, packageChanges, state.lastProcessedSubgraph, watchConfig, logger);
1333
1277
  const isRestart = action === ChangeAction.Restart;
1334
1278
  const isSequential = watchConfig.subprocess.concurrency === 1;
1335
1279
  const controller = determineAbortController(isRestart);
1336
1280
  const onProcessFailure = () => {
1337
- logger.debug(styleText10("dim", "Aborting controller: process failed."));
1281
+ logger.debug(styleText8("dim", "Aborting controller: process failed."));
1338
1282
  controller.abort();
1339
- lastProcessedSubgraph = undefined;
1283
+ state.lastProcessedSubgraph = undefined;
1340
1284
  };
1341
1285
  if (action === ChangeAction.Ignore && packageChanges.size) {
1342
1286
  logger.info(`Changes detected; but were ignored due to 'partialProcessing: true'. Waiting for changes..`);
1343
1287
  return;
1344
1288
  }
1345
1289
  if (packageChanges.size) {
1346
- logger.info(`${isRestart ? "Restarting processing" : "Initiating partial processing"} ${isSequential ? "sequentially" : `in parallel${isDefined4(watchConfig.subprocess.concurrency) ? ` with concurrency ${watchConfig.subprocess.concurrency.toString()}` : ""}`}.`);
1347
- lastProcessedSubgraph = lastProcessedSubgraph && !isRestart ? mergeGraphs(lastProcessedSubgraph, changedPackageSubgraph) : changedPackageSubgraph;
1290
+ logger.info(`${isRestart ? "Restarting processing" : "Initiating partial processing"} ${isSequential ? "sequentially" : `in parallel${isDefined3(watchConfig.subprocess.concurrency) ? ` with concurrency ${watchConfig.subprocess.concurrency.toString()}` : ""}`}.`);
1291
+ state.lastProcessedSubgraph = state.lastProcessedSubgraph && !isRestart ? mergeGraphs(state.lastProcessedSubgraph, changedPackageSubgraph) : changedPackageSubgraph;
1348
1292
  }
1349
1293
  for (const group of changedPackageProcessOrder) {
1350
1294
  await runAsync2(group.map((packageName) => async () => {
@@ -1358,7 +1302,7 @@ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determ
1358
1302
  totalProcessOrder: changedPackageProcessOrder,
1359
1303
  signal: controller.signal
1360
1304
  };
1361
- const processPackageCwd = dirname8(packageNode.packageData.path);
1305
+ const processPackageCwd = dirname6(packageNode.packageData.path);
1362
1306
  const beforeProcessPackageShellCommand = await watchConfig.hooks.onBeforeProcessPackage(processPackageProps);
1363
1307
  if (beforeProcessPackageShellCommand) {
1364
1308
  await runSubprocess({
@@ -1399,7 +1343,7 @@ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determ
1399
1343
  if (!errored) {
1400
1344
  const matchedErrorText = erroredMatcher?.push(chunk).matched();
1401
1345
  if (matchedErrorText) {
1402
- logger.error(styleText10("red", `'${packageName}' subprocess matched error text '${matchedErrorText}'.`));
1346
+ logger.error(styleText8("red", `'${packageName}' subprocess matched error text '${matchedErrorText}'.`));
1403
1347
  errored = true;
1404
1348
  Promise.resolve(watchConfig.hooks.onProcessPackageError(processPackageProps)).then((processPackageErrorCommand) => {
1405
1349
  if (!processPackageErrorCommand) {
@@ -1477,17 +1421,18 @@ var onProcessPackage = async (packageGraphs, packageChanges, watchConfig, determ
1477
1421
  };
1478
1422
  var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, logger) => {
1479
1423
  const dedupedRootPackageData = dedupeSharedPaths(packageData.map((packageData2) => packageData2.path), DedupePathsBy.Parent).map((packagePath) => assertDefined12(packageData.find((data) => data.path === packagePath)));
1480
- logger.debug(styleText10("dim", `Starting ${dedupedRootPackageData.length.toString()} watchers for ${packageData.length.toString()} packages.`));
1424
+ logger.debug(styleText8("dim", `Starting ${dedupedRootPackageData.length.toString()} watchers for ${packageData.length.toString()} packages.`));
1481
1425
  let closed = false;
1426
+ const state = { lastProcessedSubgraph: undefined };
1482
1427
  let debounceTimeout;
1483
1428
  let startedDebounceMs;
1484
1429
  let controller;
1485
- const ignoreGlobs = watchConfig.ignore ? (Array.isArray(watchConfig.ignore) ? watchConfig.ignore : [watchConfig.ignore]).map((pattern) => new Glob2(pattern)) : undefined;
1430
+ const ignoreGlobs = watchConfig.ignore ? (Array.isArray(watchConfig.ignore) ? watchConfig.ignore : [watchConfig.ignore]).map((pattern) => new Glob(pattern)) : undefined;
1486
1431
  const changedPackagePaths = new Map;
1487
1432
  const useController = (reset) => {
1488
1433
  if (controller && (reset || controller.signal.aborted)) {
1489
1434
  if (reset) {
1490
- logger.debug(styleText10("dim", "Aborting controller: reset for new packages."));
1435
+ logger.debug(styleText8("dim", "Aborting controller: reset for new packages."));
1491
1436
  controller.abort();
1492
1437
  }
1493
1438
  controller = undefined;
@@ -1501,16 +1446,16 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1501
1446
  filePath,
1502
1447
  isInitial = false
1503
1448
  }) => {
1504
- if (!isDefined4(startedDebounceMs)) {
1449
+ if (!isDefined3(startedDebounceMs)) {
1505
1450
  startedDebounceMs = Date.now();
1506
1451
  }
1507
1452
  if (packageName && watchPath && filePath) {
1508
- const changedPath = normalisePatternSeparators(join4(watchPath, normaliseWatchedFilePath(filePath)));
1453
+ const changedPath = normalisePath(join3(watchPath, normaliseWatchedFilePath(filePath)));
1509
1454
  if (ignoreGlobs?.some((glob) => glob.match(changedPath))) {
1510
- logger.debug(styleText10("dim", `Ignoring change '${changedPath}' (matched ignore pattern).`));
1455
+ logger.debug(styleText8("dim", `Ignoring change '${changedPath}' (matched ignore pattern).`));
1511
1456
  return;
1512
1457
  }
1513
- logger.debug(styleText10("dim", `Tracked change '${changedPath}'.`));
1458
+ logger.debug(styleText8("dim", `Tracked change '${changedPath}'.`));
1514
1459
  const existingPaths = changedPackagePaths.get(packageName);
1515
1460
  if (existingPaths) {
1516
1461
  existingPaths.add(changedPath);
@@ -1523,30 +1468,32 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1523
1468
  }
1524
1469
  const debounceMs = isInitial ? 0 : watchConfig.debounceMs;
1525
1470
  debounceTimeout = setTimeout(() => {
1526
- if (closed) {
1527
- return;
1528
- }
1529
- const packageChanges = new Map;
1530
- for (const [packageName2, paths] of changedPackagePaths) {
1531
- const dedupedPaths = dedupeSharedPaths(Array.from(paths), DedupePathsBy.Child).sort();
1532
- const processedPaths = filterFilesModifiedSince(dedupedPaths, assertDefined12(startedDebounceMs) - fileModifiedThresholdMs);
1533
- if (processedPaths.length) {
1534
- packageChanges.set(packageName2, processedPaths);
1471
+ (async () => {
1472
+ if (closed) {
1473
+ return;
1535
1474
  }
1536
- }
1537
- startedDebounceMs = undefined;
1538
- changedPackagePaths.clear();
1539
- if (!packageChanges.size && !isInitial) {
1540
- return;
1541
- }
1542
- onProcessPackage(packageGraphs, packageChanges, watchConfig, (reset) => useController(reset), logger);
1475
+ const packageChanges = new Map;
1476
+ for (const [packageName2, paths] of changedPackagePaths) {
1477
+ const dedupedPaths = dedupeSharedPaths(Array.from(paths), DedupePathsBy.Child).sort();
1478
+ const processedPaths = await filterFilesModifiedSince(dedupedPaths, assertDefined12(startedDebounceMs) - fileModifiedThresholdMs);
1479
+ if (processedPaths.length) {
1480
+ packageChanges.set(packageName2, processedPaths);
1481
+ }
1482
+ }
1483
+ startedDebounceMs = undefined;
1484
+ changedPackagePaths.clear();
1485
+ if (!packageChanges.size && !isInitial) {
1486
+ return;
1487
+ }
1488
+ onProcessPackage(packageGraphs, packageChanges, watchConfig, (reset) => useController(reset), state, logger);
1489
+ })();
1543
1490
  }, debounceMs);
1544
1491
  };
1545
1492
  const watchers = dedupedRootPackageData.map(({
1546
1493
  name,
1547
1494
  path
1548
1495
  }) => {
1549
- const watchPath = dirname8(path);
1496
+ const watchPath = dirname6(path);
1550
1497
  return watch(watchPath, { recursive: true }, (event, filePath) => {
1551
1498
  onWatchEvent({
1552
1499
  watchPath,
@@ -1560,12 +1507,12 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1560
1507
  watchers.forEach((watcher) => {
1561
1508
  watcher.close();
1562
1509
  });
1563
- logger.debug(styleText10("dim", "Aborting controller: closing watchers."));
1510
+ logger.debug(styleText8("dim", "Aborting controller: closing watchers."));
1564
1511
  controller?.abort();
1565
1512
  closed = true;
1566
1513
  };
1567
1514
  process.on("SIGINT", () => {
1568
- logger.debug(styleText10("dim", "Received SIGINT: closing watchers."));
1515
+ logger.debug(styleText8("dim", "Received SIGINT: closing watchers."));
1569
1516
  closeWatchers();
1570
1517
  process.exit(0);
1571
1518
  });
@@ -1583,10 +1530,10 @@ var watchPackageChanges = (packageData, packageGraphs, watchConfig, rootDir, log
1583
1530
  });
1584
1531
  return { close: () => {
1585
1532
  if (closed) {
1586
- logger.debug(styleText10("dim", "Watchers already closed."));
1533
+ logger.debug(styleText8("dim", "Watchers already closed."));
1587
1534
  return;
1588
1535
  }
1589
- logger.debug(styleText10("dim", "Closing watchers."));
1536
+ logger.debug(styleText8("dim", "Closing watchers."));
1590
1537
  closeWatchers();
1591
1538
  } };
1592
1539
  };
@@ -1599,7 +1546,7 @@ var readPackagePalConfig = (options) => {
1599
1546
  var readPackageData = async (options) => {
1600
1547
  checkBun();
1601
1548
  const packagePatterns = Array.isArray(options.config.packages) ? options.config.packages : [options.config.packages];
1602
- return loadPackages(options.rootDir, packagePatterns, options.config.logger);
1549
+ return loadPackages(options.rootDir, packagePatterns, options.adapter, options.config.logger);
1603
1550
  };
1604
1551
  var getPackageGraphs = (options) => {
1605
1552
  checkBun();
@@ -1615,9 +1562,16 @@ var getPackageCircularDependencyPaths = (options) => {
1615
1562
  };
1616
1563
  var bumpPackageVersion = (options) => {
1617
1564
  checkBun();
1618
- const exact = isDefined5(options.exact) ? options.exact : options.config.version.exact;
1619
- const preId = isDefined5(options.preId) ? options.preId : options.config.version.preId;
1620
- return updatePackageVersion(options.packageName, options.type, options.packageGraphs, preId, exact, options.config.logger);
1565
+ const exact = isDefined4(options.exact) ? options.exact : options.config.version.exact;
1566
+ const preId = isDefined4(options.preId) ? options.preId : options.config.version.preId;
1567
+ return options.adapter.updateVersion({
1568
+ packageName: options.packageName,
1569
+ type: options.type,
1570
+ packageGraphs: options.packageGraphs,
1571
+ preId,
1572
+ exact,
1573
+ logger: options.config.logger
1574
+ });
1621
1575
  };
1622
1576
  var watchPackages = (options) => {
1623
1577
  checkBun();
@@ -1629,15 +1583,18 @@ var forEachPackage = (options) => {
1629
1583
  };
1630
1584
  export {
1631
1585
  watchPackages,
1586
+ scanPackagePaths,
1632
1587
  readPackagePalConfig,
1633
1588
  readPackageData,
1634
1589
  getPackageOrder,
1635
1590
  getPackageGraphs,
1636
1591
  getPackageCircularDependencyPaths,
1637
1592
  forEachPackage,
1593
+ dfsTraverseGraph2 as dfsTraverseGraph,
1638
1594
  bumpPackageVersion,
1595
+ PackageAdapter,
1639
1596
  BumpVersionType
1640
1597
  };
1641
1598
 
1642
- //# debugId=C0E622D78585C05964756E2164756E21
1599
+ //# debugId=2C554E09012C798F64756E2164756E21
1643
1600
  //# sourceMappingURL=index.js.map