toolcrib 0.1.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/LICENSE +21 -0
- package/README.md +203 -0
- package/package.json +34 -0
- package/src/commands/apply.js +91 -0
- package/src/commands/doctor.js +178 -0
- package/src/commands/init.js +140 -0
- package/src/commands/merge.js +251 -0
- package/src/commands/versions.js +18 -0
- package/src/index.js +87 -0
- package/src/lib/bundler.js +87 -0
- package/src/lib/deps.js +74 -0
- package/src/lib/fences.js +129 -0
- package/src/lib/git.js +79 -0
- package/src/lib/github.js +102 -0
- package/src/lib/managedDocs.js +51 -0
- package/src/lib/patchFallback.js +30 -0
- package/src/lib/patches.js +120 -0
- package/src/lib/project.js +80 -0
- package/src/lib/release.js +42 -0
- package/src/lib/zip.js +65 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import * as p from '@clack/prompts';
|
|
3
|
+
import { fetchRelease } from '../lib/release.js';
|
|
4
|
+
import { PendingChanges, normalize, joinPatchPath } from '../lib/patches.js';
|
|
5
|
+
import { mergeImportsField } from '../lib/deps.js';
|
|
6
|
+
import { readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
|
|
7
|
+
import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks, upsertManagedBlock } from '../lib/managedDocs.js';
|
|
8
|
+
|
|
9
|
+
const TOOLKIT_DIR = './toolcrib';
|
|
10
|
+
// See init.js for why this exists — installs predating this entry need it
|
|
11
|
+
// added on `merge` too, not just on a fresh `init`.
|
|
12
|
+
const TOOLKIT_IMPORTS_ENTRY = { '#toolcrib': './toolcrib/index.ts' };
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Four-way classification per vendored file, comparing:
|
|
16
|
+
* - original: what was shipped in the currently-installed version
|
|
17
|
+
* - local: what's actually on disk now (possibly hand/AI-edited)
|
|
18
|
+
* - updated: what the new version ships
|
|
19
|
+
*
|
|
20
|
+
* All three are read fresh, on demand, every time — nothing here trusts
|
|
21
|
+
* a previously-cached hash (see design notes on why that was dropped).
|
|
22
|
+
*/
|
|
23
|
+
function classify(original, local, updated) {
|
|
24
|
+
const localModified = normalize(local) !== normalize(original);
|
|
25
|
+
const upstreamChanged = normalize(original) !== normalize(updated);
|
|
26
|
+
|
|
27
|
+
if (!localModified && !upstreamChanged) return 'unchanged';
|
|
28
|
+
if (!localModified && upstreamChanged) return 'safe-update';
|
|
29
|
+
if (localModified && !upstreamChanged) return 'keep-local';
|
|
30
|
+
return 'conflict';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Same classify()-based logic as the vendored-files loop below, applied to
|
|
35
|
+
* managed <!-- toolcrib:managed:... --> blocks inside AGENTS.md/CLAUDE.md
|
|
36
|
+
* instead of whole files under ./toolcrib/ — this is what makes content the
|
|
37
|
+
* user merged from ai-docs/ into their own instruction file round-trip
|
|
38
|
+
* detectable and updatable, the same way everything else already is.
|
|
39
|
+
*
|
|
40
|
+
* "original" for a given block is resolved from whatever version the block
|
|
41
|
+
* itself claims (its `version=` attribute), not necessarily oldRelease —
|
|
42
|
+
* the block may be older or newer than the currently-installed toolkit
|
|
43
|
+
* version if it was hand-edited or added out of band.
|
|
44
|
+
*/
|
|
45
|
+
async function mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes, conflicts) {
|
|
46
|
+
let updatedCount = 0;
|
|
47
|
+
let keptCount = 0;
|
|
48
|
+
|
|
49
|
+
for (const targetFile of KNOWN_TARGET_FILES) {
|
|
50
|
+
const targetPath = path.join(projectRoot, targetFile);
|
|
51
|
+
const currentFileContent = readTextIfExists(targetPath);
|
|
52
|
+
if (!currentFileContent) continue;
|
|
53
|
+
|
|
54
|
+
const blocks = listManagedBlocks(currentFileContent);
|
|
55
|
+
if (blocks.length === 0) continue;
|
|
56
|
+
|
|
57
|
+
let proposedFileContent = currentFileContent;
|
|
58
|
+
let fileChanged = false;
|
|
59
|
+
|
|
60
|
+
for (const block of blocks) {
|
|
61
|
+
const docFile = MANAGED_DOCS[block.docId];
|
|
62
|
+
if (!docFile || !newRelease.allFiles().includes(`ai-docs/${docFile}`)) continue;
|
|
63
|
+
|
|
64
|
+
let originalDocContent;
|
|
65
|
+
try {
|
|
66
|
+
if (block.version === oldRelease.version) {
|
|
67
|
+
originalDocContent = oldRelease.readFile(`ai-docs/${docFile}`);
|
|
68
|
+
} else {
|
|
69
|
+
const atVersionRelease = await fetchRelease(block.version);
|
|
70
|
+
originalDocContent = atVersionRelease.readFile(`ai-docs/${docFile}`);
|
|
71
|
+
await atVersionRelease.cleanup();
|
|
72
|
+
}
|
|
73
|
+
} catch {
|
|
74
|
+
// The version this block claims no longer resolves to a real
|
|
75
|
+
// release — can't establish drift without it. `doctor` surfaces
|
|
76
|
+
// this same situation as an explicit warning; here, just skip it
|
|
77
|
+
// rather than guess.
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const updatedDocContent = newRelease.readFile(`ai-docs/${docFile}`);
|
|
82
|
+
// block.content was already trimEnd()'d at extraction — the raw
|
|
83
|
+
// release reads above still have their trailing newline, so both
|
|
84
|
+
// must be trimmed the same way before classify() compares them, or
|
|
85
|
+
// every block registers as "conflict"/"safe-update" purely from that
|
|
86
|
+
// trailing newline rather than real content drift. See the matching
|
|
87
|
+
// fix/comment in doctor.js, where this was originally caught.
|
|
88
|
+
const status = classify(originalDocContent.trimEnd(), block.content, updatedDocContent.trimEnd());
|
|
89
|
+
|
|
90
|
+
switch (status) {
|
|
91
|
+
case 'unchanged':
|
|
92
|
+
case 'safe-update':
|
|
93
|
+
proposedFileContent = upsertManagedBlock(proposedFileContent, block.docId, newRelease.version, updatedDocContent);
|
|
94
|
+
fileChanged = fileChanged || status === 'safe-update';
|
|
95
|
+
updatedCount++;
|
|
96
|
+
break;
|
|
97
|
+
case 'keep-local':
|
|
98
|
+
keptCount++;
|
|
99
|
+
break;
|
|
100
|
+
case 'conflict':
|
|
101
|
+
// Not a vendored file under TOOLKIT_DIR, so patchPath can't be
|
|
102
|
+
// derived from relPath the way vendored-file conflicts below can
|
|
103
|
+
// — it's set explicitly here instead.
|
|
104
|
+
conflicts.push({
|
|
105
|
+
relPath: `${targetFile} (managed block "${block.docId}")`,
|
|
106
|
+
patchPath: `${targetFile}.managed-${block.docId}`,
|
|
107
|
+
original: originalDocContent,
|
|
108
|
+
local: block.content,
|
|
109
|
+
updated: updatedDocContent,
|
|
110
|
+
});
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (fileChanged) {
|
|
116
|
+
changes.propose(targetFile, currentFileContent, proposedFileContent, targetFile);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return { updatedCount, keptCount };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function mergeCommand(options) {
|
|
124
|
+
const projectRoot = process.cwd();
|
|
125
|
+
p.intro('toolcrib merge');
|
|
126
|
+
|
|
127
|
+
const lock = readLock(projectRoot);
|
|
128
|
+
if (!lock) {
|
|
129
|
+
p.log.error('No toolcrib install found (missing .toolcrib-lock.json). Run `toolcrib init` first.');
|
|
130
|
+
process.exitCode = 1;
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const spinner = p.spinner();
|
|
135
|
+
spinner.start(`Fetching current (v${lock.version}) and target (${options.version}) releases`);
|
|
136
|
+
let oldRelease, newRelease;
|
|
137
|
+
try {
|
|
138
|
+
[oldRelease, newRelease] = await Promise.all([
|
|
139
|
+
fetchRelease(lock.version),
|
|
140
|
+
fetchRelease(options.version),
|
|
141
|
+
]);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
spinner.stop('Failed to fetch releases');
|
|
144
|
+
throw err;
|
|
145
|
+
}
|
|
146
|
+
spinner.stop(`Comparing v${oldRelease.version} → v${newRelease.version}`);
|
|
147
|
+
|
|
148
|
+
if (oldRelease.version === newRelease.version) {
|
|
149
|
+
p.outro('Already on this version. Run `toolcrib doctor` to check for local drift instead.');
|
|
150
|
+
await Promise.all([oldRelease.cleanup(), newRelease.cleanup()]);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const changes = new PendingChanges();
|
|
155
|
+
const conflicts = [];
|
|
156
|
+
let updatedCount = 0;
|
|
157
|
+
let keptCount = 0;
|
|
158
|
+
|
|
159
|
+
for (const relPath of newRelease.allFiles()) {
|
|
160
|
+
const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
|
|
161
|
+
const local = readTextIfExists(targetPath);
|
|
162
|
+
const updated = newRelease.readFile(relPath);
|
|
163
|
+
// A file that's new in this release won't exist in oldRelease — treat as empty original.
|
|
164
|
+
const original = oldRelease.allFiles().includes(relPath) ? oldRelease.readFile(relPath) : '';
|
|
165
|
+
|
|
166
|
+
const status = classify(original, local, updated);
|
|
167
|
+
|
|
168
|
+
switch (status) {
|
|
169
|
+
case 'unchanged':
|
|
170
|
+
case 'safe-update':
|
|
171
|
+
changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, updated, relPath);
|
|
172
|
+
updatedCount++;
|
|
173
|
+
break;
|
|
174
|
+
case 'keep-local':
|
|
175
|
+
keptCount++;
|
|
176
|
+
break;
|
|
177
|
+
case 'conflict':
|
|
178
|
+
conflicts.push({ relPath, patchPath: joinPatchPath(TOOLKIT_DIR, relPath), original, local, updated });
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const managedBlockCounts = await mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes, conflicts);
|
|
184
|
+
updatedCount += managedBlockCounts.updatedCount;
|
|
185
|
+
keptCount += managedBlockCounts.keptCount;
|
|
186
|
+
|
|
187
|
+
await Promise.all([oldRelease.cleanup(), newRelease.cleanup()]);
|
|
188
|
+
|
|
189
|
+
// Installs from before the "imports" subpath entry existed won't have it —
|
|
190
|
+
// propose adding it here too, not just on a fresh `init`.
|
|
191
|
+
const pkgPath = path.join(projectRoot, 'package.json');
|
|
192
|
+
const userPkg = readJsonIfExists(pkgPath);
|
|
193
|
+
if (userPkg) {
|
|
194
|
+
const importsResult = mergeImportsField(userPkg, TOOLKIT_IMPORTS_ENTRY);
|
|
195
|
+
if (importsResult.changed) {
|
|
196
|
+
changes.propose(
|
|
197
|
+
'package.json',
|
|
198
|
+
readTextIfExists(pkgPath),
|
|
199
|
+
JSON.stringify(importsResult.pkg, null, 2) + '\n',
|
|
200
|
+
'package.json'
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Advance the lock file to the target version. Proposed unconditionally
|
|
206
|
+
// — the version genuinely changed (the early return above already ruled
|
|
207
|
+
// out oldRelease.version === newRelease.version), regardless of whether
|
|
208
|
+
// any individual vendored file's content also did. Without this, the
|
|
209
|
+
// lock keeps pointing at the pre-merge version forever: `doctor` would
|
|
210
|
+
// keep reporting "a newer version is available" for a version you just
|
|
211
|
+
// installed, and a later `merge` would diff from the wrong baseline,
|
|
212
|
+
// misclassifying every file that legitimately changed in this merge as
|
|
213
|
+
// a local edit — and flagging false conflicts against it next time.
|
|
214
|
+
const lockChange = proposeLockUpdate(projectRoot, newRelease.version);
|
|
215
|
+
changes.propose(lockChange.relPath, lockChange.current, lockChange.proposed, '.toolcrib-lock.json');
|
|
216
|
+
|
|
217
|
+
// Conflicts get their own patch showing the *upstream* diff (local vs.
|
|
218
|
+
// untouched), so the human/AI can see exactly what upstream changed
|
|
219
|
+
// without it silently overwriting local customizations.
|
|
220
|
+
for (const conflict of conflicts) {
|
|
221
|
+
changes.propose(
|
|
222
|
+
`${conflict.patchPath}.upstream-diff`,
|
|
223
|
+
'',
|
|
224
|
+
buildConflictNote(conflict),
|
|
225
|
+
`${conflict.relPath} (conflict)`
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (!changes.isEmpty()) {
|
|
230
|
+
await changes.writeAll(projectRoot);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
p.log.success(`${updatedCount} file(s) updated cleanly, ${keptCount} local edit(s) preserved untouched.`);
|
|
234
|
+
if (conflicts.length > 0) {
|
|
235
|
+
p.log.warn(
|
|
236
|
+
`${conflicts.length} conflict(s) — both local and upstream changed:\n` +
|
|
237
|
+
conflicts.map((c) => ` ${c.relPath}`).join('\n') +
|
|
238
|
+
`\n\nSee the .upstream-diff patch for each — ask your AI assistant to reconcile them.`
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
p.outro(changes.isEmpty() ? 'No changes to apply.' : 'Review ./toolcrib-patches/, then run `toolcrib apply`.');
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function buildConflictNote(conflict) {
|
|
246
|
+
return (
|
|
247
|
+
`This file was modified locally AND changed upstream.\n` +
|
|
248
|
+
`Automatic merge was skipped — review manually or ask your AI assistant:\n` +
|
|
249
|
+
`"reconcile my local changes to ${conflict.relPath} with the upstream update"\n`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import * as p from '@clack/prompts';
|
|
2
|
+
import { listVersions } from '../lib/github.js';
|
|
3
|
+
|
|
4
|
+
export async function versionsCommand() {
|
|
5
|
+
p.intro('toolcrib versions');
|
|
6
|
+
|
|
7
|
+
const spinner = p.spinner();
|
|
8
|
+
spinner.start('Fetching release list');
|
|
9
|
+
const versions = await listVersions();
|
|
10
|
+
spinner.stop(`Found ${versions.length} release(s)`);
|
|
11
|
+
|
|
12
|
+
for (const v of versions) {
|
|
13
|
+
const date = new Date(v.publishedAt).toLocaleDateString();
|
|
14
|
+
p.log.message(` v${v.version}${v.prerelease ? ' (prerelease)' : ''} — ${date}`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
p.outro('Use `toolcrib init --version <x.y.z>` to install a specific version.');
|
|
18
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
import { initCommand } from './commands/init.js';
|
|
4
|
+
import { mergeCommand } from './commands/merge.js';
|
|
5
|
+
import { applyCommand } from './commands/apply.js';
|
|
6
|
+
import { doctorCommand } from './commands/doctor.js';
|
|
7
|
+
import { versionsCommand } from './commands/versions.js';
|
|
8
|
+
|
|
9
|
+
const program = new Command();
|
|
10
|
+
|
|
11
|
+
// Without this, commander resolves `--version` anywhere in argv against the
|
|
12
|
+
// root program's own auto `-V, --version` flag before it ever reaches a
|
|
13
|
+
// subcommand — so `toolcrib init --version 1.2.3` silently printed the CLI's
|
|
14
|
+
// own version and exited instead of running init. Positional mode scopes an
|
|
15
|
+
// option to whichever command it's written after, letting `init`'s own
|
|
16
|
+
// `--version <version>` (a different thing: the toolkit version to install)
|
|
17
|
+
// coexist with the root flag.
|
|
18
|
+
program.enablePositionalOptions();
|
|
19
|
+
|
|
20
|
+
program
|
|
21
|
+
.name('toolcrib')
|
|
22
|
+
.description('Bootstrap and maintain the toolcrib UI toolkit in your project')
|
|
23
|
+
.version('1.0.0');
|
|
24
|
+
|
|
25
|
+
program
|
|
26
|
+
.command('init')
|
|
27
|
+
.description('Stage installation of the toolkit into the current project (writes patches, does not apply)')
|
|
28
|
+
.option('--version <version>', 'toolkit version to install', 'latest')
|
|
29
|
+
.option(
|
|
30
|
+
'--situation <situation>',
|
|
31
|
+
'also stage the matching AGENTS.md/CLAUDE.md doc block: "new" (greenfield project) or "refactor" (adopting into an existing app)'
|
|
32
|
+
)
|
|
33
|
+
.action(async (options) => {
|
|
34
|
+
await initCommand(options).catch(fail);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
program
|
|
38
|
+
.command('merge')
|
|
39
|
+
.description('Stage an update from the currently installed version to another version')
|
|
40
|
+
.option('--version <version>', 'target toolkit version', 'latest')
|
|
41
|
+
.action(async (options) => {
|
|
42
|
+
await mergeCommand(options).catch(fail);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
program
|
|
46
|
+
.command('apply')
|
|
47
|
+
.description('Apply all staged patches in ./toolcrib-patches/')
|
|
48
|
+
.action(async () => {
|
|
49
|
+
await applyCommand().catch(fail);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
program
|
|
53
|
+
.command('doctor')
|
|
54
|
+
.description('Check installed files for local drift and available updates (read-only)')
|
|
55
|
+
.action(async () => {
|
|
56
|
+
await doctorCommand().catch(fail);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
program
|
|
60
|
+
.command('versions')
|
|
61
|
+
.description('List available toolkit releases')
|
|
62
|
+
.action(async () => {
|
|
63
|
+
await versionsCommand().catch(fail);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
function fail(err) {
|
|
67
|
+
console.error(`\nError: ${err.message}`);
|
|
68
|
+
process.exitCode = 1;
|
|
69
|
+
// Setting exitCode alone isn't always enough: a codepath that leaves a
|
|
70
|
+
// spinner's setInterval running (rather than stopping it before the
|
|
71
|
+
// error propagates — see each command's own try/catch around its
|
|
72
|
+
// fetchRelease() calls) would otherwise hang the process indefinitely.
|
|
73
|
+
// But calling process.exit() immediately is worse: it force-closes every
|
|
74
|
+
// libuv handle synchronously, and on Windows this crashes with
|
|
75
|
+
// "Assertion failed: !(handle->flags & UV_HANDLE_CLOSING)" whenever a
|
|
76
|
+
// handle — concretely, the global fetch()/undici socket every command
|
|
77
|
+
// here uses to hit the GitHub API — is still mid-close from a normal
|
|
78
|
+
// failure a moment earlier. An unref'd, delayed force-exit gives normal
|
|
79
|
+
// handles time to close on their own first: if nothing else is pending,
|
|
80
|
+
// Node exits on its own before the timer ever fires; if something truly
|
|
81
|
+
// is stuck, the timer (which doesn't itself keep the process alive)
|
|
82
|
+
// still guarantees termination.
|
|
83
|
+
const forceExit = setTimeout(() => process.exit(1), 2000);
|
|
84
|
+
forceExit.unref();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
program.parse();
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Read-only signals to sniff for each bundler/framework — a config file on
|
|
6
|
+
* disk, or a package.json dependency (checked across both "dependencies"
|
|
7
|
+
* and "devDependencies", since e.g. `vite` is conventionally a devDependency
|
|
8
|
+
* but nothing stops someone declaring it otherwise). Order matters: more
|
|
9
|
+
* specific frameworks (Next.js wraps webpack; CRA wraps webpack) are
|
|
10
|
+
* checked before the generic "webpack" entry so a Next.js project reports
|
|
11
|
+
* as Next.js, not webpack.
|
|
12
|
+
*
|
|
13
|
+
* `note` is doctor-only guidance specific to that tool's actual sharp edge
|
|
14
|
+
* with this toolkit — not a generic "you're using X" announcement. `null`
|
|
15
|
+
* means detection succeeded but there's nothing this toolkit needs to warn
|
|
16
|
+
* about for that tool (e.g. Vite, since the toolkit was built against it
|
|
17
|
+
* and has no outstanding Vite-specific requirement — see safeProps.ts's
|
|
18
|
+
* bundler-agnostic dev-check).
|
|
19
|
+
*/
|
|
20
|
+
const BUNDLER_SIGNALS = [
|
|
21
|
+
{
|
|
22
|
+
id: 'next',
|
|
23
|
+
label: 'Next.js',
|
|
24
|
+
configFiles: ['next.config.js', 'next.config.mjs', 'next.config.ts'],
|
|
25
|
+
packageDeps: ['next'],
|
|
26
|
+
note:
|
|
27
|
+
"Next.js's App Router treats components as Server Components by default. Any file that renders " +
|
|
28
|
+
"toolcrib components (they use React state, context, and browser APIs) needs a `'use client'` " +
|
|
29
|
+
'directive at the top — otherwise expect a build/runtime error about hooks in a Server Component.',
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
id: 'cra',
|
|
33
|
+
label: 'Create React App',
|
|
34
|
+
configFiles: [],
|
|
35
|
+
packageDeps: ['react-scripts'],
|
|
36
|
+
note:
|
|
37
|
+
"Create React App is unmaintained and its bundled webpack config predates package.json \"imports\" " +
|
|
38
|
+
"subpath resolution — `import { ... } from '#toolcrib'` may fail to resolve at runtime, not just in " +
|
|
39
|
+
'the editor. `npm run eject` (or migrating off CRA) to gain a config you can patch is the usual fix.',
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
id: 'vite',
|
|
43
|
+
label: 'Vite',
|
|
44
|
+
configFiles: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs', 'vite.config.mts'],
|
|
45
|
+
packageDeps: ['vite'],
|
|
46
|
+
note: null,
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: 'webpack',
|
|
50
|
+
label: 'webpack',
|
|
51
|
+
configFiles: ['webpack.config.js', 'webpack.config.cjs', 'webpack.config.mjs'],
|
|
52
|
+
packageDeps: ['webpack'],
|
|
53
|
+
note:
|
|
54
|
+
'webpack 5+ resolves package.json "imports" subpaths natively; earlier major versions do not, and ' +
|
|
55
|
+
"`import { ... } from '#toolcrib'` will fail to resolve at build time on webpack 4 or older.",
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
id: 'parcel',
|
|
59
|
+
label: 'Parcel',
|
|
60
|
+
configFiles: ['.parcelrc'],
|
|
61
|
+
packageDeps: ['parcel'],
|
|
62
|
+
note: null,
|
|
63
|
+
},
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Detect the consumer's bundler/framework from signals already on disk —
|
|
68
|
+
* never asked for, matching this CLI's existing preference (see
|
|
69
|
+
* checkImportsCompatibility's tsconfig read) for deriving from real project
|
|
70
|
+
* state over interrogating the user. Returns the first matching entry's
|
|
71
|
+
* `{ id, label, note }`, or `null` if nothing recognizable is present
|
|
72
|
+
* (a legitimate outcome — plenty of projects use a bundler this list
|
|
73
|
+
* doesn't name, or none of these signals happen to be checked into the
|
|
74
|
+
* repo doctor is run from).
|
|
75
|
+
*/
|
|
76
|
+
export function detectBundler(projectRoot, pkg) {
|
|
77
|
+
const deps = { ...(pkg?.dependencies || {}), ...(pkg?.devDependencies || {}) };
|
|
78
|
+
|
|
79
|
+
for (const signal of BUNDLER_SIGNALS) {
|
|
80
|
+
const hasConfigFile = signal.configFiles.some((f) => fs.existsSync(path.join(projectRoot, f)));
|
|
81
|
+
const hasPackageDep = signal.packageDeps.some((d) => d in deps);
|
|
82
|
+
if (hasConfigFile || hasPackageDep) {
|
|
83
|
+
return { id: signal.id, label: signal.label, note: signal.note };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
package/src/lib/deps.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import semver from 'semver';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Compare a control file's required peerDependencies against what's
|
|
5
|
+
* already declared in the consumer's package.json, using real semver
|
|
6
|
+
* range intersection rather than string equality.
|
|
7
|
+
*
|
|
8
|
+
* Three buckets:
|
|
9
|
+
* - toAdd: not present at all, safe to add
|
|
10
|
+
* - compatible: present and overlaps the required range, leave alone
|
|
11
|
+
* - conflicts: present but no overlap (or an unrecognized specifier
|
|
12
|
+
* like "workspace:*" or a git URL) — needs a human decision
|
|
13
|
+
*/
|
|
14
|
+
export function resolveDependencyDecisions(userPkg, requiredDeps) {
|
|
15
|
+
const userDeps = { ...(userPkg.dependencies || {}), ...(userPkg.devDependencies || {}) };
|
|
16
|
+
|
|
17
|
+
const decisions = { toAdd: [], compatible: [], conflicts: [] };
|
|
18
|
+
|
|
19
|
+
for (const [name, requiredRange] of Object.entries(requiredDeps)) {
|
|
20
|
+
const userRange = userDeps[name];
|
|
21
|
+
|
|
22
|
+
if (!userRange) {
|
|
23
|
+
decisions.toAdd.push({ name, range: requiredRange });
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (!semver.validRange(userRange)) {
|
|
28
|
+
decisions.conflicts.push({
|
|
29
|
+
name,
|
|
30
|
+
userRange,
|
|
31
|
+
requiredRange,
|
|
32
|
+
reason: 'unrecognized version specifier — cannot verify automatically',
|
|
33
|
+
});
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (semver.intersects(userRange, requiredRange)) {
|
|
38
|
+
decisions.compatible.push({ name, userRange, requiredRange });
|
|
39
|
+
} else {
|
|
40
|
+
decisions.conflicts.push({ name, userRange, requiredRange, reason: 'version range mismatch' });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return decisions;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Produce the proposed package.json content (as an object) reflecting toAdd only. */
|
|
48
|
+
export function buildProposedPackageJson(userPkg, toAdd) {
|
|
49
|
+
const proposed = structuredClone(userPkg);
|
|
50
|
+
proposed.dependencies ??= {};
|
|
51
|
+
for (const { name, range } of toAdd) {
|
|
52
|
+
proposed.dependencies[name] = range;
|
|
53
|
+
}
|
|
54
|
+
return proposed;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Merge toolcrib's package.json "imports" subpath entry (e.g. `#toolcrib` ->
|
|
59
|
+
* `./toolcrib/index.ts`) into a package.json object, leaving any other
|
|
60
|
+
* "imports" entries the consumer already declared untouched.
|
|
61
|
+
*
|
|
62
|
+
* Returns `{ pkg, changed }` — `changed` is false when every entry is
|
|
63
|
+
* already present with the exact value expected, so callers (init/merge)
|
|
64
|
+
* can skip proposing a no-op patch.
|
|
65
|
+
*/
|
|
66
|
+
export function mergeImportsField(pkg, entry) {
|
|
67
|
+
const current = pkg.imports || {};
|
|
68
|
+
const alreadySet = Object.entries(entry).every(([key, value]) => current[key] === value);
|
|
69
|
+
if (alreadySet) return { pkg, changed: false };
|
|
70
|
+
|
|
71
|
+
const proposed = structuredClone(pkg);
|
|
72
|
+
proposed.imports = { ...current, ...entry };
|
|
73
|
+
return { pkg: proposed, changed: true };
|
|
74
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic "fence" primitives for marking CLI-managed spans inside files the
|
|
3
|
+
* CLI does not otherwise own outright — files that mix toolcrib-authored
|
|
4
|
+
* content with the user's own (AGENTS.md/CLAUDE.md, .gitignore, and
|
|
5
|
+
* eventually app source files). Different file types comment differently,
|
|
6
|
+
* so the fence syntax is parameterized by "style" rather than hardcoded to
|
|
7
|
+
* one comment form. See lib/managedDocs.js for the Markdown-specific
|
|
8
|
+
* application of this to ai-docs content merged into AGENTS.md/CLAUDE.md.
|
|
9
|
+
*
|
|
10
|
+
* Known limitation: content containing a literal occurrence of the style's
|
|
11
|
+
* own end-comment text would prematurely close the fence. Not defended
|
|
12
|
+
* against — it doesn't occur in any content this CLI currently generates,
|
|
13
|
+
* and guarding against it would add real complexity for a case that isn't
|
|
14
|
+
* happening in practice.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// \r?\n, never a bare \n, in every pattern below: `git apply` writes files
|
|
18
|
+
// with CRLF whenever core.autocrlf=true (the common Windows Git default —
|
|
19
|
+
// confirmed via a real end-to-end run where this was originally \n-only and
|
|
20
|
+
// silently matched zero blocks against a real CRLF-checked-out AGENTS.md,
|
|
21
|
+
// with no error, just silent non-detection). extractFence()/upsertFence()
|
|
22
|
+
// still return/compare content run through normalize() by their callers
|
|
23
|
+
// (doctor.js, merge.js) so a pure line-ending difference is never itself
|
|
24
|
+
// reported as drift — this fix is about matching the fence at all.
|
|
25
|
+
// Unlike vendored component source (meant to be forked/customized freely),
|
|
26
|
+
// content inside a managed fence is meant to be regenerated, not hand-edited
|
|
27
|
+
// — so every fence carries a visible warning to that effect. The warning
|
|
28
|
+
// text itself is stripped back out by extractFence() before content is
|
|
29
|
+
// returned/compared (see below), so rewording it later doesn't invalidate
|
|
30
|
+
// old fences, and it never shows up as spurious drift.
|
|
31
|
+
function bannerFor(style) {
|
|
32
|
+
const text =
|
|
33
|
+
"Auto-generated by toolcrib — do not edit by hand, it will be overwritten by 'toolcrib merge'. " +
|
|
34
|
+
'Add your own notes outside this block instead.';
|
|
35
|
+
return style === 'markdown' ? `<!-- ${text} -->` : style === 'hash' ? `# ${text}` : `// ${text}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const FENCE_STYLES = {
|
|
39
|
+
// Markdown / HTML-comment files: AGENTS.md, CLAUDE.md.
|
|
40
|
+
markdown: {
|
|
41
|
+
start: (id, version) => `<!-- toolcrib:managed:${id}:start version=${version} -->`,
|
|
42
|
+
banner: () => bannerFor('markdown'),
|
|
43
|
+
end: (id) => `<!-- toolcrib:managed:${id}:end -->`,
|
|
44
|
+
// \r?\n, never a bare \n, here and in every pattern below: `git apply`
|
|
45
|
+
// writes files with CRLF whenever core.autocrlf=true (the common
|
|
46
|
+
// Windows Git default — confirmed via a real end-to-end run where this
|
|
47
|
+
// was originally \n-only and silently matched zero blocks against a
|
|
48
|
+
// real CRLF-checked-out AGENTS.md, with no error, just silent
|
|
49
|
+
// non-detection). extractFence()/upsertFence() still return/compare
|
|
50
|
+
// content run through normalize() by their callers (doctor.js,
|
|
51
|
+
// merge.js) so a pure line-ending difference is never itself reported
|
|
52
|
+
// as drift — this is about matching the fence at all.
|
|
53
|
+
pattern: (id) =>
|
|
54
|
+
new RegExp(
|
|
55
|
+
`<!-- toolcrib:managed:${id}:start version=(\\S+) -->\\r?\\n([\\s\\S]*?)<!-- toolcrib:managed:${id}:end -->\\r?\\n?`
|
|
56
|
+
),
|
|
57
|
+
},
|
|
58
|
+
// #-comment files: .gitignore, .env, YAML, shell scripts.
|
|
59
|
+
hash: {
|
|
60
|
+
start: (id, version) => `# toolcrib:managed:${id}:start version=${version}`,
|
|
61
|
+
banner: () => bannerFor('hash'),
|
|
62
|
+
end: (id) => `# toolcrib:managed:${id}:end`,
|
|
63
|
+
pattern: (id) =>
|
|
64
|
+
new RegExp(`# toolcrib:managed:${id}:start version=(\\S+)\\r?\\n([\\s\\S]*?)# toolcrib:managed:${id}:end\\r?\\n?`),
|
|
65
|
+
},
|
|
66
|
+
// JS/TS/JSX/TSX source files. Not used by any current CLI feature — no
|
|
67
|
+
// command patches user source code yet — but defined here so a future
|
|
68
|
+
// one (e.g. auto-inserting the ThemeProvider/ToastProvider root wiring
|
|
69
|
+
// from NEW_APP.md into main.tsx) has a ready-made, consistent style
|
|
70
|
+
// rather than inventing another ad-hoc convention.
|
|
71
|
+
js: {
|
|
72
|
+
start: (id, version) => `// toolcrib:managed:${id}:start version=${version}`,
|
|
73
|
+
banner: () => bannerFor('js'),
|
|
74
|
+
end: (id) => `// toolcrib:managed:${id}:end`,
|
|
75
|
+
pattern: (id) =>
|
|
76
|
+
new RegExp(`// toolcrib:managed:${id}:start version=(\\S+)\\r?\\n([\\s\\S]*?)// toolcrib:managed:${id}:end\\r?\\n?`),
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// JSON has no comment syntax, so it cannot carry a textual fence at all —
|
|
81
|
+
// noted here rather than silently unsupported. The one JSON asset this CLI
|
|
82
|
+
// patches (package.json) is instead tracked structurally, by known
|
|
83
|
+
// dependency/imports key names (see lib/deps.js), not by an inline marker.
|
|
84
|
+
export const NO_FENCE_ASSET_TYPES = ['json'];
|
|
85
|
+
|
|
86
|
+
function escapeRegExp(text) {
|
|
87
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Build a complete fenced block (start marker, banner, content, end marker) in the given style. */
|
|
91
|
+
export function buildFence(style, id, version, content) {
|
|
92
|
+
const banner = style.banner ? `${style.banner()}\n` : '';
|
|
93
|
+
return `${style.start(id, version)}\n${banner}${content.trimEnd()}\n${style.end(id)}\n`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Find an existing fenced block for `id` in `fileContent`. Returns null if
|
|
98
|
+
* absent. The "do not edit" banner (if this style has one) is stripped from
|
|
99
|
+
* the returned content — it's a fence-structure concern, not part of the
|
|
100
|
+
* actual doc content being tracked, and leaving it in would make every
|
|
101
|
+
* block compare as different from the pristine source that never had it.
|
|
102
|
+
*/
|
|
103
|
+
export function extractFence(style, fileContent, id) {
|
|
104
|
+
const match = style.pattern(id).exec(fileContent);
|
|
105
|
+
if (!match) return null;
|
|
106
|
+
let content = match[2];
|
|
107
|
+
if (style.banner) {
|
|
108
|
+
const bannerLine = new RegExp(`^${escapeRegExp(style.banner())}\\r?\\n`);
|
|
109
|
+
content = content.replace(bannerLine, '');
|
|
110
|
+
}
|
|
111
|
+
return { version: match[1], content: content.trimEnd(), raw: match[0] };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Insert or replace the fenced block for `id` in `fileContent`.
|
|
116
|
+
* If a block for this id already exists, only that span is replaced —
|
|
117
|
+
* everything else in the file is left untouched. Otherwise the block is
|
|
118
|
+
* appended.
|
|
119
|
+
*/
|
|
120
|
+
export function upsertFence(style, fileContent, id, version, content) {
|
|
121
|
+
const newBlock = buildFence(style, id, version, content);
|
|
122
|
+
const regex = style.pattern(id);
|
|
123
|
+
if (regex.test(fileContent)) {
|
|
124
|
+
return fileContent.replace(regex, newBlock);
|
|
125
|
+
}
|
|
126
|
+
if (fileContent.length === 0) return newBlock;
|
|
127
|
+
const separator = fileContent.endsWith('\n\n') ? '' : fileContent.endsWith('\n') ? '\n' : '\n\n';
|
|
128
|
+
return fileContent + separator + newBlock;
|
|
129
|
+
}
|