@williamthorsen/nmr-core 0.7.2 → 0.8.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.
package/README.md CHANGED
@@ -4,7 +4,15 @@ Shared utilities for node-monorepo-tools packages.
4
4
 
5
5
  This package serves as the shared library foundation for the monorepo. For the nmr CLI tool, see [`@williamthorsen/nmr`](../nmr).
6
6
 
7
- <!-- section:release-notes --><!-- /section:release-notes -->
7
+ <!-- section:release-notes -->
8
+ ## Release notes — v0.8.0 (2026-08-03)
9
+
10
+ ### 🎉 Features
11
+
12
+ - Skip checks that already passed on the current working tree (#568)
13
+
14
+ `nmr` commands now skip any pure check (types, lint, tests) that has already passed on an unchanged working tree; instead, success is reported immediately. `nmr --no-cache` causes the cache check to be skipped, and `NMR_NO_CACHE=1` does the same for a whole shell. Cached results are cleared by `nmr clean`. Which commands can skip is configurable at the monorepo root, and `NMR_DEBUG=1` reports why a run didn't skip.
15
+ <!-- /section:release-notes -->
8
16
 
9
17
  ## Installation
10
18
 
@@ -13,3 +21,13 @@ Requires Node.js 24 or later.
13
21
  ```bash
14
22
  pnpm add -D @williamthorsen/nmr-core
15
23
  ```
24
+
25
+ ## The `nmr-source` export condition
26
+
27
+ Alongside the usual entry, the package declares an `nmr-source` export condition resolving to its TypeScript
28
+ source. It exists for one caller: the compiler that builds this package. That compiler imports this package, so
29
+ on a tree with no build output it has to reach the source, which is what the condition gives it.
30
+
31
+ Nothing else should pass `--conditions nmr-source`. The published package ships `dist` alone, so the condition
32
+ resolves to a file that is not in the tarball and fails with `ERR_MODULE_NOT_FOUND`. Resolution without the flag
33
+ is unaffected: an unmatched condition is skipped, and the entry resolves to the build output as it always has.
@@ -0,0 +1,15 @@
1
+ export interface CacheDirRef {
2
+ tool: string;
3
+ scopeDir: string;
4
+ }
5
+ export interface CacheEntryRef extends CacheDirRef {
6
+ slug: string;
7
+ extension: string;
8
+ discriminators?: string[];
9
+ }
10
+ export declare function readCacheEntry(entryPath: string): Promise<string | undefined>;
11
+ export declare function readJsonCacheEntry<T>(entryPath: string, isValidEntry: (value: unknown) => value is T): Promise<T | undefined>;
12
+ export declare function removeCacheDir(ref: CacheDirRef): Promise<void>;
13
+ export declare function resolveCacheDir(ref: CacheDirRef): string;
14
+ export declare function resolveCacheEntryPath(ref: CacheEntryRef): string;
15
+ export declare function writeCacheEntry(entryPath: string, content: string): Promise<void>;
@@ -0,0 +1,71 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ const DIGEST_LENGTH = 8;
6
+ export async function readCacheEntry(entryPath) {
7
+ try {
8
+ return await readFile(entryPath, 'utf8');
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ }
14
+ export async function readJsonCacheEntry(entryPath, isValidEntry) {
15
+ const raw = await readCacheEntry(entryPath);
16
+ if (raw === undefined) {
17
+ return undefined;
18
+ }
19
+ let parsed;
20
+ try {
21
+ parsed = JSON.parse(raw);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ return isValidEntry(parsed) ? parsed : undefined;
27
+ }
28
+ export async function removeCacheDir(ref) {
29
+ await rm(resolveCacheDir(ref), { force: true, recursive: true });
30
+ }
31
+ export function resolveCacheDir(ref) {
32
+ const absoluteScopeDir = path.resolve(ref.scopeDir);
33
+ const home = findNearestNodeModulesHost(absoluteScopeDir) ?? absoluteScopeDir;
34
+ return path.join(home, 'node_modules', '.cache', ref.tool);
35
+ }
36
+ export function resolveCacheEntryPath(ref) {
37
+ const absoluteScopeDir = path.resolve(ref.scopeDir);
38
+ const digest = createHash('sha256')
39
+ .update([absoluteScopeDir, ...(ref.discriminators ?? [])].join('\0'))
40
+ .digest('hex')
41
+ .slice(0, DIGEST_LENGTH);
42
+ return path.join(resolveCacheDir(ref), `${ref.slug}-${digest}${ref.extension}`);
43
+ }
44
+ export async function writeCacheEntry(entryPath, content) {
45
+ await mkdir(path.dirname(entryPath), { recursive: true });
46
+ const temporaryPath = `${entryPath}.${randomUUID()}.tmp`;
47
+ try {
48
+ await writeFile(temporaryPath, content);
49
+ await rename(temporaryPath, entryPath);
50
+ }
51
+ catch (error) {
52
+ try {
53
+ await unlink(temporaryPath);
54
+ }
55
+ catch {
56
+ }
57
+ throw error;
58
+ }
59
+ }
60
+ function findNearestNodeModulesHost(startDir) {
61
+ let current = startDir;
62
+ let parent = path.dirname(current);
63
+ while (!existsSync(path.join(current, 'node_modules'))) {
64
+ if (parent === current) {
65
+ return undefined;
66
+ }
67
+ current = parent;
68
+ parent = path.dirname(current);
69
+ }
70
+ return current;
71
+ }
@@ -0,0 +1,11 @@
1
+ export type WorkingTreeHashResult = {
2
+ ok: true;
3
+ hash: string;
4
+ headSha: string;
5
+ toplevel: string;
6
+ } | {
7
+ ok: false;
8
+ reason: string;
9
+ };
10
+ export declare function hashWorkingTree(cwd: string): WorkingTreeHashResult;
11
+ export declare function readHeadSha(cwd: string): string | undefined;
@@ -0,0 +1,163 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, lstatSync, readFileSync, readlinkSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ const HASH_FORMAT = 'nmr-working-tree-v1';
6
+ const GIT_OUTPUT_LIMIT = 64 * 1024 * 1024;
7
+ const PRECEDING_FIELD_COUNTS = {
8
+ 1: 8,
9
+ 2: 9,
10
+ '?': 1,
11
+ u: 10,
12
+ };
13
+ const SUBMODULE_BEARING_TYPES = new Set(['1', '2', 'u']);
14
+ export function hashWorkingTree(cwd) {
15
+ const toplevelResult = runGit(['rev-parse', '--show-toplevel'], cwd);
16
+ if (!toplevelResult.ok) {
17
+ return { ok: false, reason: `not a git repository: ${toplevelResult.error}` };
18
+ }
19
+ const toplevel = toplevelResult.stdout.trim();
20
+ if (toplevel === '') {
21
+ return { ok: false, reason: 'git reported no repository toplevel' };
22
+ }
23
+ if (existsSync(path.join(toplevel, '.gitmodules'))) {
24
+ return { ok: false, reason: 'the repository declares submodules, whose content this hash does not cover' };
25
+ }
26
+ const revisionResult = runGit(['rev-parse', 'HEAD', 'HEAD^{tree}'], cwd);
27
+ if (!revisionResult.ok) {
28
+ return { ok: false, reason: `no commit at HEAD: ${revisionResult.error}` };
29
+ }
30
+ const [headSha, headTreeSha] = revisionResult.stdout.trim().split('\n', 2);
31
+ if (headSha === undefined || headTreeSha === undefined) {
32
+ return { ok: false, reason: 'git reported no HEAD commit and tree' };
33
+ }
34
+ const statusResult = runGit(['status', '--porcelain=v2', '-z', '--untracked-files=all'], cwd);
35
+ if (!statusResult.ok) {
36
+ return { ok: false, reason: `git status failed: ${statusResult.error}` };
37
+ }
38
+ const pathsResult = collectChangedPaths(statusResult.stdout);
39
+ if (!pathsResult.ok) {
40
+ return pathsResult;
41
+ }
42
+ const hash = createHash('sha256');
43
+ hash.update(HASH_FORMAT);
44
+ hash.update('\0');
45
+ hash.update(headTreeSha);
46
+ hash.update('\0');
47
+ for (const relativePath of [...pathsResult.paths].sort()) {
48
+ const content = digestPathContent(toplevel, relativePath);
49
+ if (!content.ok) {
50
+ return content;
51
+ }
52
+ hash.update(relativePath);
53
+ hash.update('\0');
54
+ hash.update(content.kind);
55
+ hash.update('\0');
56
+ hash.update(content.digest);
57
+ hash.update('\0');
58
+ }
59
+ return { ok: true, hash: hash.digest('hex'), headSha, toplevel };
60
+ }
61
+ export function readHeadSha(cwd) {
62
+ const result = runGit(['rev-parse', 'HEAD'], cwd);
63
+ if (!result.ok) {
64
+ return undefined;
65
+ }
66
+ const headSha = result.stdout.trim();
67
+ return headSha === '' ? undefined : headSha;
68
+ }
69
+ function collectChangedPaths(statusOutput) {
70
+ const records = statusOutput.split('\0');
71
+ const paths = new Set();
72
+ for (let index = 0; index < records.length; index++) {
73
+ const record = records[index];
74
+ if (record === undefined || record === '') {
75
+ continue;
76
+ }
77
+ const type = record.slice(0, 1);
78
+ if (type === '#') {
79
+ continue;
80
+ }
81
+ if (SUBMODULE_BEARING_TYPES.has(type) && extractField(record, 2)?.startsWith('S') === true) {
82
+ return { ok: false, reason: 'the working tree holds a submodule, whose content this hash does not cover' };
83
+ }
84
+ const precedingFieldCount = PRECEDING_FIELD_COUNTS[type];
85
+ if (precedingFieldCount === undefined) {
86
+ return { ok: false, reason: `unrecognized git status record: ${JSON.stringify(record.slice(0, 40))}` };
87
+ }
88
+ const changedPath = extractPath(record, precedingFieldCount);
89
+ if (changedPath === undefined) {
90
+ return { ok: false, reason: `malformed git status record: ${JSON.stringify(record.slice(0, 40))}` };
91
+ }
92
+ paths.add(changedPath);
93
+ if (type === '2') {
94
+ index++;
95
+ const originalPath = records[index];
96
+ if (originalPath === undefined || originalPath === '') {
97
+ return { ok: false, reason: 'git status reported a rename with no original path' };
98
+ }
99
+ paths.add(originalPath);
100
+ }
101
+ }
102
+ return { ok: true, paths };
103
+ }
104
+ function describeError(error) {
105
+ return error instanceof Error ? error.message : String(error);
106
+ }
107
+ function digestBuffer(buffer) {
108
+ return createHash('sha256').update(buffer).digest('hex');
109
+ }
110
+ function digestPathContent(toplevel, relativePath) {
111
+ const absolutePath = path.join(toplevel, relativePath);
112
+ let stats;
113
+ try {
114
+ stats = lstatSync(absolutePath);
115
+ }
116
+ catch (error) {
117
+ if (isErrorWithCode(error, 'ENOENT')) {
118
+ return { ok: true, kind: 'absent', digest: '' };
119
+ }
120
+ return { ok: false, reason: `could not stat ${relativePath}: ${describeError(error)}` };
121
+ }
122
+ try {
123
+ if (stats.isSymbolicLink()) {
124
+ return { ok: true, kind: 'link', digest: digestBuffer(Buffer.from(readlinkSync(absolutePath))) };
125
+ }
126
+ if (stats.isFile()) {
127
+ return { ok: true, kind: 'file', digest: digestBuffer(readFileSync(absolutePath)) };
128
+ }
129
+ }
130
+ catch (error) {
131
+ return { ok: false, reason: `could not read ${relativePath}: ${describeError(error)}` };
132
+ }
133
+ return { ok: false, reason: `${relativePath} is neither a file nor a symlink, so its content is not hashable` };
134
+ }
135
+ function extractField(record, fieldIndex) {
136
+ return record.split(' ')[fieldIndex];
137
+ }
138
+ function extractPath(record, precedingFieldCount) {
139
+ let index = 0;
140
+ for (let field = 0; field < precedingFieldCount; field++) {
141
+ const separator = record.indexOf(' ', index);
142
+ if (separator === -1) {
143
+ return undefined;
144
+ }
145
+ index = separator + 1;
146
+ }
147
+ const extracted = record.slice(index);
148
+ return extracted === '' ? undefined : extracted;
149
+ }
150
+ function isErrorWithCode(error, code) {
151
+ return error instanceof Error && 'code' in error && error.code === code;
152
+ }
153
+ function runGit(args, cwd) {
154
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: GIT_OUTPUT_LIMIT });
155
+ if (result.error) {
156
+ return { ok: false, error: result.error.message };
157
+ }
158
+ if (result.status !== 0) {
159
+ const stderr = result.stderr.trim();
160
+ return { ok: false, error: stderr || `\`git ${args.join(' ')}\` failed with exit code ${result.status}.` };
161
+ }
162
+ return { ok: true, stdout: result.stdout };
163
+ }
@@ -1,5 +1,9 @@
1
1
  export declare const PACKAGE_NAME = "@williamthorsen/nmr-core";
2
+ export type { CacheDirRef, CacheEntryRef } from './cache-store.js';
3
+ export { readCacheEntry, readJsonCacheEntry, removeCacheDir, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, } from './cache-store.js';
2
4
  export { findPackageRoot } from './findPackageRoot.js';
5
+ export type { WorkingTreeHashResult } from './hashWorkingTree.js';
6
+ export { hashWorkingTree, readHeadSha } from './hashWorkingTree.js';
3
7
  export type { FlagDefinition, FlagSchema, ParseArgsOptions, ParsedArgs, ParsedFlags, ParseErrorKind, } from './parseArgs.js';
4
8
  export { parseArgs, parseArgsOrExit, ParseError } from './parseArgs.js';
5
9
  export { readPackageVersion } from './readPackageVersion.js';
package/dist/esm/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  export const PACKAGE_NAME = '@williamthorsen/nmr-core';
2
+ export { readCacheEntry, readJsonCacheEntry, removeCacheDir, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, } from "./cache-store.js";
2
3
  export { findPackageRoot } from "./findPackageRoot.js";
4
+ export { hashWorkingTree, readHeadSha } from "./hashWorkingTree.js";
3
5
  export { parseArgs, parseArgsOrExit, ParseError } from "./parseArgs.js";
4
6
  export { readPackageVersion } from "./readPackageVersion.js";
5
7
  export { formatErrorLine, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, } from "./terminal.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@williamthorsen/nmr-core",
3
- "version": "0.7.2",
3
+ "version": "0.8.0",
4
4
  "private": false,
5
5
  "description": "Shared utilities for node-monorepo-tools packages",
6
6
  "keywords": [
@@ -22,6 +22,7 @@
22
22
  "type": "module",
23
23
  "exports": {
24
24
  ".": {
25
+ "nmr-source": "./src/index.ts",
25
26
  "types": "./dist/esm/index.d.ts",
26
27
  "default": "./dist/esm/index.js"
27
28
  }