@williamthorsen/nmr-core 0.11.1 → 0.13.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.
@@ -1,4 +1,68 @@
1
1
  [
2
+ {
3
+ "version": "0.13.0",
4
+ "date": "2026-09-22",
5
+ "sections": [
6
+ {
7
+ "title": "🎉 Features",
8
+ "audience": "all",
9
+ "items": [
10
+ {
11
+ "description": "Hoist the pnpm-workspace resolver into nmr-core as a total API (#864)",
12
+ "body": "- Adds a `./workspace` subpath export to `@williamthorsen/nmr-core`, whose `resolveWorkspace` returns a pnpm workspace's package directories, or the cause of an empty result, as a value rather than as a thrown error.\n- Reports a `pnpm-workspace.yaml` that the YAML parser rejects under a cause of its own, `unreadable-manifest`, so `nmr -R build` names the syntax error and its remedy in place of failing with the parser's own error.\n- Removes `diagnoseEmptyWorkspace` and `EmptyWorkspaceDiagnosis` from `@williamthorsen/nmr/workspace`, since `resolveWorkspace` reports the same cause in one call.\n\nMigration: Replace each `diagnoseEmptyWorkspace` call with `resolveWorkspace`, which reports the cause on the empty result it already returns, and rename the `no-manifest` cause to `no-package`. `EmptyWorkspaceCause` also gains `unreadable-manifest`, so an exhaustive switch over it stops compiling until it handles the new member; every other export of `@williamthorsen/nmr/workspace` keeps its signature and its `UserError` throws.",
13
+ "breaking": true,
14
+ "migration": "Replace each `diagnoseEmptyWorkspace` call with `resolveWorkspace`, which reports the cause on the empty result it already returns, and rename the `no-manifest` cause to `no-package`. `EmptyWorkspaceCause` also gains `unreadable-manifest`, so an exhaustive switch over it stops compiling until it handles the new member; every other export of `@williamthorsen/nmr/workspace` keeps its signature and its `UserError` throws.",
15
+ "hash": "3196b84c9d5f037ead0e98ee8547fe71e80fb5c6"
16
+ },
17
+ {
18
+ "description": "Adopt the shared workspace resolver in release-kit, honoring exclusions (#865)",
19
+ "body": "- 🚨 **Breaking:** Narrows `no-pattern` in `@williamthorsen/nmr-core`'s `EmptyWorkspaceCause`, moving an absent or empty `packages` list onto `no-packages-list` and a value that is not a list of strings onto `unreadable-packages`.\n- Stops `release-kit` from tagging, publishing, and label-syncing a package that a `!` entry in `pnpm-workspace.yaml` excludes, which its previous `glob`-based resolution could not remove from the match.\n- Replaces the release of the root package alone with a failure naming the condition that emptied the workspace, when `pnpm-workspace.yaml` does not hold valid YAML or declares a workspace that does not resolve to a package.\n- Replaces the `no-pattern` remedy that `nmr` printed for a `pnpm-workspace.yaml` declaring no `packages` list, and for one declaring a `packages` value that is not a list of strings.\n- Raises `engines.node` to `>=24.16.0` in `@williamthorsen/nmr-core` and `@williamthorsen/release-kit`, because Node 24.0 through 24.15 ignores the `followSymlinks` option that the workspace matcher passes to `globSync` and drops a symlinked package directory from the resolution without reporting it.\n\nMigration: Add a `no-packages-list` arm and an `unreadable-packages` arm to any `switch` that covers `EmptyWorkspaceCause` exhaustively. `no-pattern` now names only a list that the resolver read in full and whose entries all failed to become a positive pattern, so move the handling of an absent `packages` key, an empty list, and a value that is not a list of strings out of the `no-pattern` arm into the two new ones. Route `no-packages-list` to single-package behavior rather than to a failure path: pnpm resolves such a manifest to the root package alone.",
20
+ "breaking": true,
21
+ "migration": "Add a `no-packages-list` arm and an `unreadable-packages` arm to any `switch` that covers `EmptyWorkspaceCause` exhaustively. `no-pattern` now names only a list that the resolver read in full and whose entries all failed to become a positive pattern, so move the handling of an absent `packages` key, an empty list, and a value that is not a list of strings out of the `no-pattern` arm into the two new ones. Route `no-packages-list` to single-package behavior rather than to a failure path: pnpm resolves such a manifest to the root package alone.",
22
+ "hash": "b1126866159402b8f027a9b82f2a19591a6e9e1b"
23
+ }
24
+ ]
25
+ },
26
+ {
27
+ "title": "🐛 Bug fixes",
28
+ "audience": "all",
29
+ "items": [
30
+ {
31
+ "description": "Truncate release-kit commit subjects by display column (#840)",
32
+ "body": "- Fixes the issue that the `release-kit` prepare report cut a commit subject at 69 UTF-16 code units instead of at display columns, so a subject of CJK characters printed about twice the intended 72-column width and a cut inside an emoji left a broken character that a terminal drew as a replacement glyph.\n- Replaces the `...` marker on a truncated subject with `…`, the default of the width-aware truncation that now does the cutting.\n- Exports `truncateToWidth` and `measureWidth` from `@williamthorsen/nmr-core`, which measure and cut text by display width without splitting a grapheme cluster.",
33
+ "hash": "f75d9b4abd9fbda264d5dd40ca5b7abb64f5a3f3"
34
+ }
35
+ ]
36
+ }
37
+ ]
38
+ },
39
+ {
40
+ "version": "0.12.0",
41
+ "date": "2026-09-18",
42
+ "sections": [
43
+ {
44
+ "title": "🎉 Features",
45
+ "audience": "all",
46
+ "items": [
47
+ {
48
+ "description": "Give nmr-core's print helpers plain output in pipes and CI logs (#834)",
49
+ "body": "- Stops `printError`, `printSkip`, `printSuccess`, and `reportWriteResult` in `@williamthorsen/nmr-core` from printing emoji into a pipe or a CI log: Each helper now detects a plain or rich style from `CI` and the terminal state of its own stream (stderr for `printError`, stdout for the others), and accepts an optional trailing `OutputStyle` that outranks detection.\n- Adds `resolveStreamStyles`, which resolves a `plain` or `rich` output style separately for stdout and stderr, reading a caller-named flag first, then a caller-named environment variable (`auto`, `plain`, or `rich`), then `CI`, the stream's terminal state, and `TERM`, and which returns a setting that it does not recognize in `invalid` instead of throwing.\n- Re-exports `defineGlyphSet`, `STATUS_GLYPHS`, `wrapToWidth`, `measureGlyphColumn`, and `describeInvalidOutputStyle` from the experimental `/candidate` API of `@williamthorsen/toolbelt.terminal`, so that a package that depends on `@williamthorsen/nmr-core` builds glyph sets and wraps text without declaring that dependency itself.\n- Changes the rich marker of `printSkip` from ⚠️ to 🟠, the `warning` glyph in `STATUS_GLYPHS`; rich `printError` and `printSuccess` output is unchanged.",
50
+ "hash": "0c45461848b6c7bfee5a28be2a1cb2633ccdddfe"
51
+ },
52
+ {
53
+ "description": "Give release-kit plain output in pipes and CI logs (#835)",
54
+ "body": "- Adds the `RELEASE_KIT_OUTPUT_STYLE` environment variable, which accepts `auto`, `plain`, or `rich` and outranks the detection from `CI`, the stream's terminal state, and `TERM`; any other value is a usage error that exits with code 1.\n- Changes the emoji in rich output so that none has a different meaning from the one that it has in `nmr`: warnings from ⚠️ to 🟠, skips from ⏭️ to ⏩, the errors of `show-tag-prefixes` from ⛔ to ❌, and the tag marker from 🏷️ to 🔖.\n- Adds a required `style` parameter to `formatValidateOverridesResult`, which the package root exports.",
55
+ "hash": "aae401b4bbcafc7014e4b3804d80528d2d098a30"
56
+ },
57
+ {
58
+ "description": "Give nmr plain output in pipes and CI logs (#838)",
59
+ "body": "- Stops `nmr` from printing emoji to a pipe or a CI log: When the output stream is not a terminal or `CI` is set, a verdict reads `PASS`, `FAIL`, `SKIP`, or `NOOP` and a command icon is omitted, so that a log can be searched for a verdict.\n- Adds `--output-style <auto|plain|rich>` to `nmr` and the `NMR_OUTPUT_STYLE` variable, each forcing either style; the flag outranks the variable, a value that names no style exits 1 with a usage error, and neither enters a check-cache key: A rich run and a plain run share a recorded pass.\n- Replaces several rich glyphs, taking the status markers from the set that release-kit and v11y-check print so that one status has one glyph across the three tools: a recalled pass shows ⏩ in place of ⏭️, a skipped empty override shows ⚪ in place of ⛔, a warning and the `--log` refusal show 🟠 in place of ⚠️ and 📭, the `--log` header shows 💾 in place of 📼, and `nmr-ensure-prepublish-hooks` reports ✅ and ❌ in place of ✓ and ✗.",
60
+ "hash": "693b3a7f57def3d299ced240c19bda90f6253bdc"
61
+ }
62
+ ]
63
+ }
64
+ ]
65
+ },
2
66
  {
3
67
  "version": "0.11.1",
4
68
  "date": "2026-09-15",
package/CHANGELOG.md CHANGED
@@ -2,6 +2,59 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## 0.13.0 — 2026-09-22
6
+
7
+ ### 🎉 Features
8
+
9
+ - 🚨 **Breaking:** Hoist the pnpm-workspace resolver into nmr-core as a total API (#864)
10
+
11
+ - Adds a `./workspace` subpath export to `@williamthorsen/nmr-core`, whose `resolveWorkspace` returns a pnpm workspace's package directories, or the cause of an empty result, as a value rather than as a thrown error.
12
+ - Reports a `pnpm-workspace.yaml` that the YAML parser rejects under a cause of its own, `unreadable-manifest`, so `nmr -R build` names the syntax error and its remedy in place of failing with the parser's own error.
13
+ - Removes `diagnoseEmptyWorkspace` and `EmptyWorkspaceDiagnosis` from `@williamthorsen/nmr/workspace`, since `resolveWorkspace` reports the same cause in one call.
14
+
15
+ Migration: Replace each `diagnoseEmptyWorkspace` call with `resolveWorkspace`, which reports the cause on the empty result it already returns, and rename the `no-manifest` cause to `no-package`. `EmptyWorkspaceCause` also gains `unreadable-manifest`, so an exhaustive switch over it stops compiling until it handles the new member; every other export of `@williamthorsen/nmr/workspace` keeps its signature and its `UserError` throws.
16
+
17
+ - 🚨 **Breaking:** Adopt the shared workspace resolver in release-kit, honoring exclusions (#865)
18
+
19
+ - 🚨 **Breaking:** Narrows `no-pattern` in `@williamthorsen/nmr-core`'s `EmptyWorkspaceCause`, moving an absent or empty `packages` list onto `no-packages-list` and a value that is not a list of strings onto `unreadable-packages`.
20
+ - Stops `release-kit` from tagging, publishing, and label-syncing a package that a `!` entry in `pnpm-workspace.yaml` excludes, which its previous `glob`-based resolution could not remove from the match.
21
+ - Replaces the release of the root package alone with a failure naming the condition that emptied the workspace, when `pnpm-workspace.yaml` does not hold valid YAML or declares a workspace that does not resolve to a package.
22
+ - Replaces the `no-pattern` remedy that `nmr` printed for a `pnpm-workspace.yaml` declaring no `packages` list, and for one declaring a `packages` value that is not a list of strings.
23
+ - Raises `engines.node` to `>=24.16.0` in `@williamthorsen/nmr-core` and `@williamthorsen/release-kit`, because Node 24.0 through 24.15 ignores the `followSymlinks` option that the workspace matcher passes to `globSync` and drops a symlinked package directory from the resolution without reporting it.
24
+
25
+ Migration: Add a `no-packages-list` arm and an `unreadable-packages` arm to any `switch` that covers `EmptyWorkspaceCause` exhaustively. `no-pattern` now names only a list that the resolver read in full and whose entries all failed to become a positive pattern, so move the handling of an absent `packages` key, an empty list, and a value that is not a list of strings out of the `no-pattern` arm into the two new ones. Route `no-packages-list` to single-package behavior rather than to a failure path: pnpm resolves such a manifest to the root package alone.
26
+
27
+ ### 🐛 Bug fixes
28
+
29
+ - Truncate release-kit commit subjects by display column (#840)
30
+
31
+ - Fixes the issue that the `release-kit` prepare report cut a commit subject at 69 UTF-16 code units instead of at display columns, so a subject of CJK characters printed about twice the intended 72-column width and a cut inside an emoji left a broken character that a terminal drew as a replacement glyph.
32
+ - Replaces the `...` marker on a truncated subject with `…`, the default of the width-aware truncation that now does the cutting.
33
+ - Exports `truncateToWidth` and `measureWidth` from `@williamthorsen/nmr-core`, which measure and cut text by display width without splitting a grapheme cluster.
34
+
35
+ ## 0.12.0 — 2026-09-18
36
+
37
+ ### 🎉 Features
38
+
39
+ - Give nmr-core's print helpers plain output in pipes and CI logs (#834)
40
+
41
+ - Stops `printError`, `printSkip`, `printSuccess`, and `reportWriteResult` in `@williamthorsen/nmr-core` from printing emoji into a pipe or a CI log: Each helper now detects a plain or rich style from `CI` and the terminal state of its own stream (stderr for `printError`, stdout for the others), and accepts an optional trailing `OutputStyle` that outranks detection.
42
+ - Adds `resolveStreamStyles`, which resolves a `plain` or `rich` output style separately for stdout and stderr, reading a caller-named flag first, then a caller-named environment variable (`auto`, `plain`, or `rich`), then `CI`, the stream's terminal state, and `TERM`, and which returns a setting that it does not recognize in `invalid` instead of throwing.
43
+ - Re-exports `defineGlyphSet`, `STATUS_GLYPHS`, `wrapToWidth`, `measureGlyphColumn`, and `describeInvalidOutputStyle` from the experimental `/candidate` API of `@williamthorsen/toolbelt.terminal`, so that a package that depends on `@williamthorsen/nmr-core` builds glyph sets and wraps text without declaring that dependency itself.
44
+ - Changes the rich marker of `printSkip` from ⚠️ to 🟠, the `warning` glyph in `STATUS_GLYPHS`; rich `printError` and `printSuccess` output is unchanged.
45
+
46
+ - Give release-kit plain output in pipes and CI logs (#835)
47
+
48
+ - Adds the `RELEASE_KIT_OUTPUT_STYLE` environment variable, which accepts `auto`, `plain`, or `rich` and outranks the detection from `CI`, the stream's terminal state, and `TERM`; any other value is a usage error that exits with code 1.
49
+ - Changes the emoji in rich output so that none has a different meaning from the one that it has in `nmr`: warnings from ⚠️ to 🟠, skips from ⏭️ to ⏩, the errors of `show-tag-prefixes` from ⛔ to ❌, and the tag marker from 🏷️ to 🔖.
50
+ - Adds a required `style` parameter to `formatValidateOverridesResult`, which the package root exports.
51
+
52
+ - Give nmr plain output in pipes and CI logs (#838)
53
+
54
+ - Stops `nmr` from printing emoji to a pipe or a CI log: When the output stream is not a terminal or `CI` is set, a verdict reads `PASS`, `FAIL`, `SKIP`, or `NOOP` and a command icon is omitted, so that a log can be searched for a verdict.
55
+ - Adds `--output-style <auto|plain|rich>` to `nmr` and the `NMR_OUTPUT_STYLE` variable, each forcing either style; the flag outranks the variable, a value that names no style exits 1 with a usage error, and neither enters a check-cache key: A rich run and a plain run share a recorded pass.
56
+ - Replaces several rich glyphs, taking the status markers from the set that release-kit and v11y-check print so that one status has one glyph across the three tools: a recalled pass shows ⏩ in place of ⏭️, a skipped empty override shows ⚪ in place of ⛔, a warning and the `--log` refusal show 🟠 in place of ⚠️ and 📭, the `--log` header shows 💾 in place of 📼, and `nmr-ensure-prepublish-hooks` reports ✅ and ❌ in place of ✓ and ✗.
57
+
5
58
  ## 0.11.1 — 2026-09-15
6
59
 
7
60
  ### ⚙️ Tooling
package/README.md CHANGED
@@ -1,10 +1,42 @@
1
+ <!-- readme-type: library -->
2
+
1
3
  # @williamthorsen/nmr-core
2
4
 
3
5
  Shared utilities for node-monorepo-tools packages.
4
6
 
5
7
  This package serves as the shared library foundation for the monorepo. For the nmr CLI tool, see [`@williamthorsen/nmr`](../nmr).
6
8
 
7
- <!-- section:release-notes --><!-- /section:release-notes -->
9
+ <!-- section:release-notes -->
10
+ ## Release notes — v0.13.0 (2026-09-22)
11
+
12
+ ### 🎉 Features
13
+
14
+ - 🚨 **Breaking:** Hoist the pnpm-workspace resolver into nmr-core as a total API (#864)
15
+
16
+ - Adds a `./workspace` subpath export to `@williamthorsen/nmr-core`, whose `resolveWorkspace` returns a pnpm workspace's package directories, or the cause of an empty result, as a value rather than as a thrown error.
17
+ - Reports a `pnpm-workspace.yaml` that the YAML parser rejects under a cause of its own, `unreadable-manifest`, so `nmr -R build` names the syntax error and its remedy in place of failing with the parser's own error.
18
+ - Removes `diagnoseEmptyWorkspace` and `EmptyWorkspaceDiagnosis` from `@williamthorsen/nmr/workspace`, since `resolveWorkspace` reports the same cause in one call.
19
+
20
+ Migration: Replace each `diagnoseEmptyWorkspace` call with `resolveWorkspace`, which reports the cause on the empty result it already returns, and rename the `no-manifest` cause to `no-package`. `EmptyWorkspaceCause` also gains `unreadable-manifest`, so an exhaustive switch over it stops compiling until it handles the new member; every other export of `@williamthorsen/nmr/workspace` keeps its signature and its `UserError` throws.
21
+
22
+ - 🚨 **Breaking:** Adopt the shared workspace resolver in release-kit, honoring exclusions (#865)
23
+
24
+ - 🚨 **Breaking:** Narrows `no-pattern` in `@williamthorsen/nmr-core`'s `EmptyWorkspaceCause`, moving an absent or empty `packages` list onto `no-packages-list` and a value that is not a list of strings onto `unreadable-packages`.
25
+ - Stops `release-kit` from tagging, publishing, and label-syncing a package that a `!` entry in `pnpm-workspace.yaml` excludes, which its previous `glob`-based resolution could not remove from the match.
26
+ - Replaces the release of the root package alone with a failure naming the condition that emptied the workspace, when `pnpm-workspace.yaml` does not hold valid YAML or declares a workspace that does not resolve to a package.
27
+ - Replaces the `no-pattern` remedy that `nmr` printed for a `pnpm-workspace.yaml` declaring no `packages` list, and for one declaring a `packages` value that is not a list of strings.
28
+ - Raises `engines.node` to `>=24.16.0` in `@williamthorsen/nmr-core` and `@williamthorsen/release-kit`, because Node 24.0 through 24.15 ignores the `followSymlinks` option that the workspace matcher passes to `globSync` and drops a symlinked package directory from the resolution without reporting it.
29
+
30
+ Migration: Add a `no-packages-list` arm and an `unreadable-packages` arm to any `switch` that covers `EmptyWorkspaceCause` exhaustively. `no-pattern` now names only a list that the resolver read in full and whose entries all failed to become a positive pattern, so move the handling of an absent `packages` key, an empty list, and a value that is not a list of strings out of the `no-pattern` arm into the two new ones. Route `no-packages-list` to single-package behavior rather than to a failure path: pnpm resolves such a manifest to the root package alone.
31
+
32
+ ### 🐛 Bug fixes
33
+
34
+ - Truncate release-kit commit subjects by display column (#840)
35
+
36
+ - Fixes the issue that the `release-kit` prepare report cut a commit subject at 69 UTF-16 code units instead of at display columns, so a subject of CJK characters printed about twice the intended 72-column width and a cut inside an emoji left a broken character that a terminal drew as a replacement glyph.
37
+ - Replaces the `...` marker on a truncated subject with `…`, the default of the width-aware truncation that now does the cutting.
38
+ - Exports `truncateToWidth` and `measureWidth` from `@williamthorsen/nmr-core`, which measure and cut text by display width without splitting a grapheme cluster.
39
+ <!-- /section:release-notes -->
8
40
 
9
41
  ## Installation
10
42
 
@@ -14,12 +46,22 @@ Requires Node.js 24 or later.
14
46
  pnpm add -D @williamthorsen/nmr-core
15
47
  ```
16
48
 
49
+ ## Workspace introspection
50
+
51
+ The `./workspace` entry publishes the pnpm-workspace lookups that nmr and release-kit share. Every one of them
52
+ is total: it returns a value rather than throwing, so each CLI keeps its own error boundary.
53
+ [Workspace introspection](../nmr/docs/workspace.md) documents what each lookup returns and where it diverges
54
+ from pnpm.
55
+
56
+ The entry stays out of the root export, which keeps `yaml` out of the module closure of every other importer,
57
+ the build bootstrap's included.
58
+
17
59
  ## The `nmr-source` export condition
18
60
 
19
- Alongside the usual entry, the package declares an `nmr-source` export condition resolving to its TypeScript
20
- source. It exists for one caller: the compiler that builds this package. That compiler imports this package, so
21
- on a tree with no build output it has to reach the source, which is what the condition gives it.
61
+ Both entries declare an `nmr-source` export condition resolving to their TypeScript source. It exists for one
62
+ caller: the compiler that builds this package. That compiler imports this package, so on a tree with no build
63
+ output it has to reach the source, which is what the condition gives it.
22
64
 
23
65
  Nothing else should pass `--conditions nmr-source`. The published package ships `dist` alone, so the condition
24
66
  resolves to a file that is not in the tarball and fails with `ERR_MODULE_NOT_FOUND`. Resolution without the flag
25
- is unaffected: an unmatched condition is skipped, and the entry resolves to the build output as it always has.
67
+ is unaffected: an unmatched condition is skipped, and each entry resolves to the build output as it always has.
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The manifest patterns a declared `packages` list resolves to, split by what each entry asks of the matcher.
3
+ *
4
+ * Held as manifest patterns rather than as the entries themselves, so a caller re-matching a subset spends the
5
+ * same rewriting a full resolution does.
6
+ */
7
+ export interface WorkspacePatternSplit {
8
+ excludedPatterns: string[];
9
+ includedPatterns: string[];
10
+ }
11
+ /**
12
+ * Matches manifest patterns against a monorepo root, returning the absolute directories that hold a matched
13
+ * manifest, sorted and free of duplicates.
14
+ *
15
+ * Takes the exclusion set as an argument of its own, so a caller diagnosing an empty resolution can re-match
16
+ * the positive patterns alone and learn whether the exclusions are what emptied it.
17
+ */
18
+ export declare function matchPackageDirs(monorepoRoot: string, includedPatterns: readonly string[], excludedPatterns: readonly string[]): string[];
19
+ /**
20
+ * Resolves pnpm workspace patterns to absolute package directories.
21
+ *
22
+ * Applies pnpm's algorithm: every pattern is rewritten to match a manifest, `!`-prefixed patterns become
23
+ * exclusions, and the matcher decides the rest. Exclusions filter the entire positive match set
24
+ * irrespective of declaration order.
25
+ */
26
+ export declare function resolvePackageDirs(monorepoRoot: string, patterns: readonly string[]): string[];
27
+ /**
28
+ * Splits a declared `packages` list into the manifest patterns the matcher includes and the ones it excludes.
29
+ *
30
+ * The sole reader of what counts as a positive pattern, shared by a resolution and by a diagnosis of its empty
31
+ * result: two readers classifying entries separately could disagree about which condition a manifest is in.
32
+ */
33
+ export declare function splitWorkspacePatterns(patterns: readonly string[]): WorkspacePatternSplit;
@@ -0,0 +1,36 @@
1
+ import { globSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ const MANIFEST = 'package.json';
4
+ const ALWAYS_EXCLUDED = ['**/node_modules/**'];
5
+ export function matchPackageDirs(monorepoRoot, includedPatterns, excludedPatterns) {
6
+ const options = {
7
+ cwd: monorepoRoot,
8
+ exclude: [...excludedPatterns, ...ALWAYS_EXCLUDED],
9
+ followSymlinks: true,
10
+ };
11
+ const matches = globSync([...includedPatterns], options);
12
+ const dirs = matches.map((match) => path.dirname(path.resolve(monorepoRoot, match)));
13
+ return [...new Set(dirs)].toSorted();
14
+ }
15
+ export function resolvePackageDirs(monorepoRoot, patterns) {
16
+ const { excludedPatterns, includedPatterns } = splitWorkspacePatterns(patterns);
17
+ if (includedPatterns.length === 0) {
18
+ return [];
19
+ }
20
+ return matchPackageDirs(monorepoRoot, includedPatterns, excludedPatterns);
21
+ }
22
+ export function splitWorkspacePatterns(patterns) {
23
+ const includedPatterns = [];
24
+ const excludedPatterns = [];
25
+ for (const pattern of patterns) {
26
+ if (pattern.trim() === '')
27
+ continue;
28
+ const isNegated = pattern.startsWith('!');
29
+ const target = isNegated ? excludedPatterns : includedPatterns;
30
+ target.push(buildManifestPattern(isNegated ? pattern.slice(1) : pattern));
31
+ }
32
+ return { excludedPatterns, includedPatterns };
33
+ }
34
+ function buildManifestPattern(pattern) {
35
+ return `${pattern.replace(/\/?$/, '')}/${MANIFEST}`;
36
+ }
@@ -9,6 +9,7 @@ export { hashWorkingTree, readHeadSha } from './hashWorkingTree.js';
9
9
  export type { FlagDefinition, FlagSchema, ParseArgsOptions, ParsedArgs, ParsedFlags, ParseErrorKind, } from './parseArgs.js';
10
10
  export { parseArgs, parseArgsOrExit, ParseError } from './parseArgs.js';
11
11
  export { readPackageVersion } from './readPackageVersion.js';
12
- export { formatErrorLine, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, } from './terminal.js';
12
+ export type { GlyphSet, InvalidOutputStyle, OutputStyle, ResolveStreamStylesOptions, StatusGlyphName, StreamStyleResolution, StreamStyles, TruncateToWidthOptions, } from './terminal.js';
13
+ export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
13
14
  export type { WriteOutcome, WriteResult } from './writeFileWithCheck.js';
14
15
  export { writeFileWithCheck } from './writeFileWithCheck.js';
package/dist/esm/index.js CHANGED
@@ -6,5 +6,5 @@ export { hasErrnoCode } from "./hasErrnoCode.js";
6
6
  export { hashWorkingTree, readHeadSha } from "./hashWorkingTree.js";
7
7
  export { parseArgs, parseArgsOrExit, ParseError } from "./parseArgs.js";
8
8
  export { readPackageVersion } from "./readPackageVersion.js";
9
- export { formatErrorLine, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, } from "./terminal.js";
9
+ export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
10
10
  export { writeFileWithCheck } from "./writeFileWithCheck.js";
@@ -1,24 +1,65 @@
1
1
  import type { Writable } from 'node:stream';
2
+ import { type GlyphSet, type InvalidOutputStyle, type OutputStyle, type StatusGlyphName } from '@williamthorsen/toolbelt.terminal/candidate';
2
3
  import type { WriteResult } from './writeFileWithCheck.js';
4
+ export type { GlyphSet, InvalidOutputStyle, OutputStyle, StatusGlyphName, TruncateToWidthOptions, } from '@williamthorsen/toolbelt.terminal/candidate';
5
+ export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, measureWidth, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
6
+ export interface ResolveStreamStylesOptions {
7
+ /** Raw arguments in which to find `flag`; read only when `flag` is given. */
8
+ readonly argv?: readonly string[] | undefined;
9
+ readonly env: Readonly<Record<string, string | undefined>>;
10
+ /** The environment variable holding the caller's standing preference: `auto`, `plain`, or `rich`. */
11
+ readonly envVar: string;
12
+ /** The flag naming a style for one invocation, leading dashes included; it outranks `envVar`. */
13
+ readonly flag?: string | undefined;
14
+ readonly stderrIsTty: boolean;
15
+ readonly stdoutIsTty: boolean;
16
+ }
17
+ export interface StreamStyleResolution {
18
+ /** The first value of `flag` or `envVar` that names no setting; resolution continues with the next source. */
19
+ readonly invalid?: InvalidOutputStyle | undefined;
20
+ readonly styles: StreamStyles;
21
+ }
22
+ export interface StreamStyles {
23
+ readonly stderr: OutputStyle;
24
+ readonly stdout: OutputStyle;
25
+ }
3
26
  /**
4
27
  * Renders the canonical `Error: <message>` line (without a trailing newline) — the single
5
28
  * definition of this shape. Use it where the line is a value rather than a write target,
6
29
  * e.g. a command that returns its message for the caller to print.
7
30
  */
8
31
  export declare function formatErrorLine(message: string): string;
9
- /** Prints an error message to stderr. */
10
- export declare function printError(message: string): void;
11
- /** Prints a skip/warning message to stdout. */
12
- export declare function printSkip(message: string): void;
32
+ /**
33
+ * Renders a glyph from `glyphs` and a message, omitting the separating space when the glyph's variant is
34
+ * empty, which is what a set declares for a name whose message always opens on a word.
35
+ */
36
+ export declare function formatGlyphLine<Name extends string>(glyphs: GlyphSet<Name>, style: OutputStyle, name: Name, message: string): string;
37
+ /** Renders a status marker and a message, padding the marker so that messages align across statuses. */
38
+ export declare function formatStatusLine(style: OutputStyle, status: StatusGlyphName, message: string): string;
39
+ /** Prints an error message to stderr, in the style detected for stderr unless one is given. */
40
+ export declare function printError(message: string, style?: OutputStyle): void;
41
+ /** Prints a skip/warning message to stdout, in the style detected for stdout unless one is given. */
42
+ export declare function printSkip(message: string, style?: OutputStyle): void;
13
43
  /** Prints a step label with a right-arrow prefix. */
14
44
  export declare function printStep(message: string): void;
15
- /** Prints a success message with a checkmark emoji prefix. */
16
- export declare function printSuccess(message: string): void;
45
+ /** Prints a success message to stdout, in the style detected for stdout unless one is given. */
46
+ export declare function printSuccess(message: string, style?: OutputStyle): void;
17
47
  /**
18
48
  * Writes the canonical `Error: <message>` line to a stream (stderr by default) — the single
19
49
  * sanctioned door for this output shape. Pass an injected stream for in-process CLIs that
20
50
  * route output through a `Writable` rather than touching `process.stderr` directly.
21
51
  */
22
52
  export declare function reportError(message: string, stream?: Writable): void;
23
- /** Prints a terminal message for a write result based on its outcome. */
24
- export declare function reportWriteResult(result: WriteResult, dryRun: boolean): void;
53
+ /**
54
+ * Prints a terminal message for a write result based on its outcome: a failure to stderr, every
55
+ * other outcome to stdout. Each message takes its own stream's style from `styles`; without
56
+ * `styles`, it takes the style detected for that stream.
57
+ */
58
+ export declare function reportWriteResult(result: WriteResult, dryRun: boolean, styles?: StreamStyles): void;
59
+ /**
60
+ * Resolves the style of each output stream: the flag when one is named, else the named environment
61
+ * variable, else detection from `CI`, the stream's terminal state, and `TERM`. Never throws; a value
62
+ * that names no setting is returned in `invalid`, for the caller to report with
63
+ * `describeInvalidOutputStyle`.
64
+ */
65
+ export declare function resolveStreamStyles(options: ResolveStreamStylesOptions): StreamStyleResolution;
@@ -1,58 +1,81 @@
1
1
  import process from 'node:process';
2
+ import { detectOutputStyle, measureGlyphColumn, resolveOutputStyle, STATUS_GLYPHS, } from '@williamthorsen/toolbelt.terminal/candidate';
3
+ export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, measureWidth, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
2
4
  export function formatErrorLine(message) {
3
5
  return `Error: ${message}`;
4
6
  }
5
- export function printError(message) {
6
- process.stderr.write(` ❌ ${message}\n`);
7
+ export function formatGlyphLine(glyphs, style, name, message) {
8
+ const { text } = glyphs[style][name];
9
+ return text === '' ? message : `${text} ${message}`;
7
10
  }
8
- export function printSkip(message) {
9
- console.info(` ⚠️ ${message}`);
11
+ export function formatStatusLine(style, status, message) {
12
+ const glyphs = STATUS_GLYPHS[style];
13
+ const glyph = glyphs[status];
14
+ const padding = ' '.repeat(measureGlyphColumn(glyphs) - glyph.width);
15
+ return `${glyph.text}${padding} ${message}`;
16
+ }
17
+ export function printError(message, style = detectStreamStyle(process.stderr)) {
18
+ process.stderr.write(` ${formatStatusLine(style, 'failed', message)}\n`);
19
+ }
20
+ export function printSkip(message, style = detectStreamStyle(process.stdout)) {
21
+ console.info(` ${formatStatusLine(style, 'warning', message)}`);
10
22
  }
11
23
  export function printStep(message) {
12
24
  console.info(`\n> ${message}`);
13
25
  }
14
- export function printSuccess(message) {
15
- console.info(` ✅ ${message}`);
26
+ export function printSuccess(message, style = detectStreamStyle(process.stdout)) {
27
+ console.info(` ${formatStatusLine(style, 'passed', message)}`);
16
28
  }
17
29
  export function reportError(message, stream = process.stderr) {
18
30
  stream.write(`${formatErrorLine(message)}\n`);
19
31
  }
20
- export function reportWriteResult(result, dryRun) {
32
+ export function reportWriteResult(result, dryRun, styles) {
33
+ const style = styles?.stdout;
21
34
  switch (result.outcome) {
22
35
  case 'created':
23
36
  if (dryRun) {
24
- printSuccess(`[dry-run] Would create ${result.filePath}`);
37
+ printSuccess(`[dry-run] Would create ${result.filePath}`, style);
25
38
  }
26
39
  else {
27
- printSuccess(`Created ${result.filePath}`);
40
+ printSuccess(`Created ${result.filePath}`, style);
28
41
  }
29
42
  break;
30
43
  case 'overwritten':
31
44
  if (dryRun) {
32
- printSuccess(`[dry-run] Would overwrite ${result.filePath}`);
45
+ printSuccess(`[dry-run] Would overwrite ${result.filePath}`, style);
33
46
  }
34
47
  else {
35
- printSuccess(`Overwrote ${result.filePath}`);
48
+ printSuccess(`Overwrote ${result.filePath}`, style);
36
49
  }
37
50
  break;
38
51
  case 'up-to-date':
39
- printSuccess(`${result.filePath} (up to date)`);
52
+ printSuccess(`${result.filePath} (up to date)`, style);
40
53
  break;
41
54
  case 'skipped':
42
55
  if (result.error) {
43
- printSkip(`${result.filePath} (could not read for comparison: ${result.error})`);
56
+ printSkip(`${result.filePath} (could not read for comparison: ${result.error})`, style);
44
57
  }
45
58
  else {
46
- printSkip(`${result.filePath} (already exists)`);
59
+ printSkip(`${result.filePath} (already exists)`, style);
47
60
  }
48
61
  break;
49
62
  case 'failed':
50
63
  if (result.error) {
51
- printError(`Failed to write ${result.filePath}: ${result.error}`);
64
+ printError(`Failed to write ${result.filePath}: ${result.error}`, styles?.stderr);
52
65
  }
53
66
  else {
54
- printError(`Failed to write ${result.filePath}`);
67
+ printError(`Failed to write ${result.filePath}`, styles?.stderr);
55
68
  }
56
69
  break;
57
70
  }
58
71
  }
72
+ export function resolveStreamStyles(options) {
73
+ const { argv = [], env, envVar, flag, stderrIsTty, stdoutIsTty } = options;
74
+ const stderr = resolveOutputStyle({ argv, env, envVar, flag, isTty: stderrIsTty });
75
+ const stdout = resolveOutputStyle({ argv, env, envVar, flag, isTty: stdoutIsTty });
76
+ const styles = { stderr: stderr.style, stdout: stdout.style };
77
+ return stdout.invalid === undefined ? { styles } : { invalid: stdout.invalid, styles };
78
+ }
79
+ function detectStreamStyle(stream) {
80
+ return detectOutputStyle({ env: process.env, isTty: stream.isTTY === true });
81
+ }
@@ -0,0 +1,68 @@
1
+ /** Which of six conditions left a workspace resolving to no package directory. */
2
+ export type EmptyWorkspaceCause = 'all-excluded' | 'no-package' | 'no-packages-list' | 'no-pattern' | 'unreadable-manifest' | 'unreadable-packages';
3
+ /**
4
+ * What resolving a directory's workspace patterns produced: the directory declares no workspace, it resolves
5
+ * to a set of package directories, or it resolves to none and the cause says which condition emptied it.
6
+ *
7
+ * The declared patterns travel with the last two because a message composed from one quotes them back to the
8
+ * reader. They are empty under `unreadable-manifest`, the one cause whose manifest declares nothing the reader
9
+ * can see.
10
+ */
11
+ export type WorkspaceResolution = {
12
+ kind: 'empty';
13
+ cause: EmptyWorkspaceCause;
14
+ patterns: string[];
15
+ } | {
16
+ kind: 'not-a-workspace';
17
+ } | {
18
+ kind: 'packages';
19
+ packageDirs: string[];
20
+ patterns: string[];
21
+ };
22
+ /**
23
+ * Finds the monorepo root by walking up from `startDir`, defaulting to `process.cwd()`, until it reaches a
24
+ * directory holding `pnpm-workspace.yaml`.
25
+ *
26
+ * Returns nothing where the walk runs out of parent directories, which a CLI turns into whichever failure its
27
+ * own error boundary calls for.
28
+ */
29
+ export declare function findMonorepoRoot(startDir?: string): string | undefined;
30
+ /** Reports whether a directory is the monorepo root, which the workspace manifest's presence marks. */
31
+ export declare function isMonorepoRoot(dir: string): boolean;
32
+ /**
33
+ * Reads the `overrides` block from the monorepo root's `pnpm-workspace.yaml`, the site pnpm reads an override
34
+ * from.
35
+ *
36
+ * Returns nothing when the manifest is missing, unreadable, unparseable, or declares no block, and drops an
37
+ * entry whose value is not a string.
38
+ */
39
+ export declare function readWorkspaceOverrides(monorepoRoot: string): Record<string, string> | undefined;
40
+ /**
41
+ * Reads the manifest `name` each of the given package directories declares, which is what a `-F` pattern
42
+ * matches.
43
+ *
44
+ * A directory whose manifest is missing, unparseable, or nameless contributes nothing. The sweep runs for a
45
+ * diagnostic's sake, so one malformed manifest elsewhere in the workspace must not replace the diagnostic the
46
+ * reader asked for with a failure of its own.
47
+ */
48
+ export declare function readWorkspacePackageNames(packageDirs: readonly string[]): string[];
49
+ /**
50
+ * Resolves the workspace a directory declares, applying pnpm's pattern semantics — including `!`-prefixed
51
+ * exclusions — and reporting which condition left the result empty.
52
+ *
53
+ * Reaches the filesystem a second time for `all-excluded` alone, re-matching the positive patterns without the
54
+ * exclusion set. That runs only where a resolution has already come back empty.
55
+ *
56
+ * Three causes separate what a manifest declares from what the reader could make of it, because one remedy
57
+ * does not answer them all. `no-packages-list` is a manifest declaring nothing, an absent `packages` key or an
58
+ * empty list, which pnpm resolves to the root package alone; `unreadable-packages` is a `packages` value that
59
+ * is not a list of strings, which declares something the reader refused; and `no-pattern` is a list whose
60
+ * entries all fail to become a positive pattern, `!` entries and entries YAML emptied. A caller treating an
61
+ * empty resolution as a failure needs the first held apart from the other two, and a caller composing a
62
+ * message needs all three.
63
+ *
64
+ * A manifest that the reader cannot parse at all is `unreadable-manifest`. It declares whatever it declares,
65
+ * and the remedy the pattern causes share — declare a positive pattern — repairs nothing for a reader who has
66
+ * one and a syntax error above it.
67
+ */
68
+ export declare function resolveWorkspace(monorepoRoot: string): WorkspaceResolution;
@@ -0,0 +1,111 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { matchPackageDirs, resolvePackageDirs, splitWorkspacePatterns } from "./helpers/workspace-patterns.js";
5
+ const PACKAGE_MANIFEST = 'package.json';
6
+ const WORKSPACE_MANIFEST = 'pnpm-workspace.yaml';
7
+ export function findMonorepoRoot(startDir) {
8
+ let dir = path.resolve(startDir ?? process.cwd());
9
+ for (;;) {
10
+ if (isMonorepoRoot(dir)) {
11
+ return dir;
12
+ }
13
+ const parent = path.dirname(dir);
14
+ if (parent === dir) {
15
+ return undefined;
16
+ }
17
+ dir = parent;
18
+ }
19
+ }
20
+ export function isMonorepoRoot(dir) {
21
+ return existsSync(path.join(dir, WORKSPACE_MANIFEST));
22
+ }
23
+ export function readWorkspaceOverrides(monorepoRoot) {
24
+ const manifestRead = readWorkspaceManifest(monorepoRoot);
25
+ if (manifestRead.kind !== 'parsed' || !isObject(manifestRead.value)) {
26
+ return undefined;
27
+ }
28
+ const overrides = manifestRead.value['overrides'];
29
+ return isObject(overrides) ? readStringValues(overrides) : undefined;
30
+ }
31
+ export function readWorkspacePackageNames(packageDirs) {
32
+ const names = [];
33
+ for (const dir of packageDirs) {
34
+ let parsedManifest;
35
+ try {
36
+ parsedManifest = JSON.parse(readFileSync(path.join(dir, PACKAGE_MANIFEST), 'utf8'));
37
+ }
38
+ catch {
39
+ continue;
40
+ }
41
+ if (isObject(parsedManifest) && typeof parsedManifest['name'] === 'string') {
42
+ names.push(parsedManifest['name']);
43
+ }
44
+ }
45
+ return names;
46
+ }
47
+ export function resolveWorkspace(monorepoRoot) {
48
+ const manifestRead = readWorkspaceManifest(monorepoRoot);
49
+ if (manifestRead.kind === 'absent') {
50
+ return { kind: 'not-a-workspace' };
51
+ }
52
+ if (manifestRead.kind === 'unreadable') {
53
+ return { cause: 'unreadable-manifest', kind: 'empty', patterns: [] };
54
+ }
55
+ const packagesRead = readDeclaredPackages(manifestRead.value);
56
+ if (packagesRead.kind !== 'patterns') {
57
+ const cause = packagesRead.kind === 'absent' ? 'no-packages-list' : 'unreadable-packages';
58
+ return { cause, kind: 'empty', patterns: [] };
59
+ }
60
+ const { patterns } = packagesRead;
61
+ const packageDirs = resolvePackageDirs(monorepoRoot, patterns);
62
+ if (packageDirs.length > 0) {
63
+ return { kind: 'packages', packageDirs, patterns };
64
+ }
65
+ return { cause: diagnoseEmptyCause(monorepoRoot, patterns), kind: 'empty', patterns };
66
+ }
67
+ function diagnoseEmptyCause(monorepoRoot, patterns) {
68
+ const { excludedPatterns, includedPatterns } = splitWorkspacePatterns(patterns);
69
+ if (includedPatterns.length === 0) {
70
+ return 'no-pattern';
71
+ }
72
+ if (excludedPatterns.length > 0 && matchPackageDirs(monorepoRoot, includedPatterns, []).length > 0) {
73
+ return 'all-excluded';
74
+ }
75
+ return 'no-package';
76
+ }
77
+ function readDeclaredPackages(parsedManifest) {
78
+ if (!isObject(parsedManifest))
79
+ return { kind: 'absent' };
80
+ const packages = parsedManifest['packages'];
81
+ if (packages === undefined || packages === null)
82
+ return { kind: 'absent' };
83
+ if (!Array.isArray(packages))
84
+ return { kind: 'unreadable' };
85
+ if (!packages.every((entry) => typeof entry === 'string'))
86
+ return { kind: 'unreadable' };
87
+ return packages.length === 0 ? { kind: 'absent' } : { kind: 'patterns', patterns: packages };
88
+ }
89
+ function isObject(value) {
90
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
91
+ }
92
+ function readStringValues(record) {
93
+ const result = {};
94
+ for (const [key, value] of Object.entries(record)) {
95
+ if (typeof value === 'string')
96
+ result[key] = value;
97
+ }
98
+ return result;
99
+ }
100
+ function readWorkspaceManifest(monorepoRoot) {
101
+ const workspaceFile = path.join(monorepoRoot, WORKSPACE_MANIFEST);
102
+ if (!existsSync(workspaceFile)) {
103
+ return { kind: 'absent' };
104
+ }
105
+ try {
106
+ return { kind: 'parsed', value: parse(readFileSync(workspaceFile, 'utf8')) };
107
+ }
108
+ catch {
109
+ return { kind: 'unreadable' };
110
+ }
111
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@williamthorsen/nmr-core",
3
- "version": "0.11.1",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "description": "Shared utilities for node-monorepo-tools packages",
6
6
  "keywords": [
@@ -26,6 +26,11 @@
26
26
  "nmr-source": "./src/index.ts",
27
27
  "types": "./dist/esm/index.d.ts",
28
28
  "default": "./dist/esm/index.js"
29
+ },
30
+ "./workspace": {
31
+ "nmr-source": "./src/workspace.ts",
32
+ "types": "./dist/esm/workspace.d.ts",
33
+ "default": "./dist/esm/workspace.js"
29
34
  }
30
35
  },
31
36
  "files": [
@@ -34,16 +39,18 @@
34
39
  "dist"
35
40
  ],
36
41
  "dependencies": {
37
- "@williamthorsen/toolbelt.errors": "0.7.0"
42
+ "@williamthorsen/toolbelt.errors": "0.8.1",
43
+ "@williamthorsen/toolbelt.terminal": "0.2.0",
44
+ "yaml": "2.9.1"
38
45
  },
39
46
  "devDependencies": {
40
- "@williamthorsen/toolbelt.filesystem": "0.8.3",
41
- "@williamthorsen/toolbelt.testing": "0.5.1",
42
- "@williamthorsen/toolbelt.vitest": "0.9.0",
47
+ "@williamthorsen/toolbelt.filesystem": "0.9.1",
48
+ "@williamthorsen/toolbelt.testing": "0.6.1",
49
+ "@williamthorsen/toolbelt.vitest": "0.10.1",
43
50
  "vitest": "4.1.11"
44
51
  },
45
52
  "engines": {
46
- "node": ">=24"
53
+ "node": ">=24.16.0"
47
54
  },
48
55
  "publishConfig": {
49
56
  "access": "public"