toolcrib 0.2.0 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolcrib",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Bootstrap the toolcrib UI toolkit into your project",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -2,10 +2,11 @@ import path from 'node:path';
2
2
  import * as p from '@clack/prompts';
3
3
  import { fetchRelease } from '../lib/release.js';
4
4
  import { normalize } from '../lib/patches.js';
5
- import { readJsonIfExists, readLock, readTextIfExists } from '../lib/project.js';
5
+ import { readJsonIfExists, readLock, readTextIfExists, fileExists } from '../lib/project.js';
6
6
  import { listVersions } from '../lib/github.js';
7
7
  import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks } from '../lib/managedDocs.js';
8
8
  import { detectBundler } from '../lib/bundler.js';
9
+ import { checkRootProviderWired } from '../lib/rootProvider.js';
9
10
 
10
11
  const TOOLKIT_DIR = './toolcrib';
11
12
 
@@ -33,6 +34,25 @@ export function checkImportsCompatibility(projectRoot) {
33
34
  return moduleResolution;
34
35
  }
35
36
 
37
+ /**
38
+ * Read-only heuristic: does this project appear to be a TypeScript project
39
+ * at all? Absence of `tsconfig.json` is the same signal
40
+ * `checkImportsCompatibility` already treats as "nothing to check here,
41
+ * e.g. a plain JS project" — this check exists specifically to make that
42
+ * case non-silent instead. toolcrib's own components are fully typed so
43
+ * that an invalid prop value (a typo'd `variant`, a misspelled event name,
44
+ * a prop that doesn't exist on that component) fails at compile time —
45
+ * a `.jsx`/`.js` consumer gets none of that, since `tsc` doesn't
46
+ * type-check plain JS by default. Confirmed as a real failure mode, not
47
+ * hypothetical: a real consumer app passed `variant="solid"` — not a
48
+ * value any toolcrib `Button` variant accepts — and it shipped invisibly
49
+ * for the life of the project until it happened to visually collide with
50
+ * an unrelated layout change and got noticed by eye.
51
+ */
52
+ export function checkTypeScriptAdopted(projectRoot) {
53
+ return fileExists(path.join(projectRoot, 'tsconfig.json'));
54
+ }
55
+
36
56
  /**
37
57
  * Read-only drift check for managed <!-- toolcrib:managed:... --> blocks
38
58
  * inside AGENTS.md/CLAUDE.md — the same question the vendored-file drift
@@ -212,6 +232,16 @@ export async function doctorCommand(options = {}) {
212
232
  p.log.info('You are on the latest release.');
213
233
  }
214
234
 
235
+ if (!checkTypeScriptAdopted(projectRoot)) {
236
+ p.log.warn(
237
+ 'No tsconfig.json found — this project doesn\'t appear to be using TypeScript. ' +
238
+ 'Every toolcrib component ships a full, exact prop type specifically so an invalid value ' +
239
+ '(a typo\'d variant, a misspelled event name, a prop that doesn\'t exist) fails at compile ' +
240
+ 'time instead of shipping silently — a plain JS/JSX project gets none of that protection. ' +
241
+ 'See NEW_APP.md\'s "Already started in JavaScript?" section to convert.'
242
+ );
243
+ }
244
+
215
245
  const badModuleResolution = checkImportsCompatibility(projectRoot);
216
246
  if (badModuleResolution !== null) {
217
247
  p.log.warn(
@@ -229,5 +259,21 @@ export async function doctorCommand(options = {}) {
229
259
  p.log.info(`Detected ${bundler.label} — ${bundler.note}`);
230
260
  }
231
261
 
262
+ const rootProvider = checkRootProviderWired(projectRoot);
263
+ if (rootProvider.found) {
264
+ p.log.success(
265
+ rootProvider.via === 'ToolcribProvider'
266
+ ? 'Root providers: <ToolcribProvider> found.'
267
+ : 'Root providers: manual <ThemeProvider>/<ToastProvider>/<ToastContainer> composition found.'
268
+ );
269
+ } else {
270
+ p.log.warn(
271
+ "Root providers: couldn't find <ToolcribProvider> or a manual <ThemeProvider>/<ToastProvider>/<ToastContainer> " +
272
+ 'composition anywhere under src/. Every toolcrib component throws or silently no-ops without one of these ' +
273
+ "wrapping your app root — see CORE.md §1. (Heuristic text scan — a false warning is possible if your root " +
274
+ 'setup uses an unusual file layout or a re-exported alias; verify directly if you believe it\'s already wired.)'
275
+ );
276
+ }
277
+
232
278
  p.outro('Done.');
233
279
  }
@@ -175,6 +175,14 @@ export async function initCommand(options) {
175
175
 
176
176
  function reportConflicts(depDecisions) {
177
177
  if (depDecisions.conflicts.length === 0) return;
178
+ // Matches doctor.js/merge.js: both set process.exitCode = 1 for their own
179
+ // "needs a human/AI decision" states. init.js previously didn't, which
180
+ // meant a real dependency conflict (e.g. a React major outside toolcrib's
181
+ // supported range) and a fully clean init were indistinguishable to
182
+ // anything checking the exit code — a script, CI step, or an agent
183
+ // deciding whether to proceed unattended. The warning text alone isn't
184
+ // enough if nothing downstream ever inspects stdout for it.
185
+ process.exitCode = 1;
178
186
  p.log.warn(
179
187
  `${depDecisions.conflicts.length} dependency conflict(s) — not staged, needs your decision:\n` +
180
188
  depDecisions.conflicts
@@ -3,7 +3,7 @@ import * as p from '@clack/prompts';
3
3
  import { fetchRelease } from '../lib/release.js';
4
4
  import { PendingChanges, normalize, joinPatchPath } from '../lib/patches.js';
5
5
  import { mergeImportsField } from '../lib/deps.js';
6
- import { readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
6
+ import { fileExists, readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
7
7
  import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks, upsertManagedBlock } from '../lib/managedDocs.js';
8
8
 
9
9
  const TOOLKIT_DIR = './toolcrib';
@@ -155,6 +155,7 @@ export async function mergeCommand(options) {
155
155
  const conflicts = [];
156
156
  let updatedCount = 0;
157
157
  let keptCount = 0;
158
+ let deletedCount = 0;
158
159
 
159
160
  for (const relPath of newRelease.allFiles()) {
160
161
  const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
@@ -180,6 +181,48 @@ export async function mergeCommand(options) {
180
181
  }
181
182
  }
182
183
 
184
+ // A file present in oldRelease but absent from newRelease was removed
185
+ // upstream — e.g. useAnimatedMount.ts when Drawer moved to Radix
186
+ // Presence in v0.10.0. Without this pass, a vendored copy of a file
187
+ // upstream no longer ships just sits there forever, unreferenced but
188
+ // never cleaned up, since the loop above only ever visits paths that
189
+ // still exist in the *new* release. classify(original, local, '')
190
+ // reuses the same four-way logic as the update loop, treating "removed
191
+ // upstream" as updated content of '': local unmodified from original ->
192
+ // safe to delete; local modified -> a real conflict (don't silently
193
+ // discard someone's customization just because upstream dropped the
194
+ // file), same as any other conflicting edit.
195
+ for (const relPath of oldRelease.allFiles()) {
196
+ if (newRelease.allFiles().includes(relPath)) continue;
197
+
198
+ const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
199
+ if (!fileExists(targetPath)) continue; // already absent locally — nothing to propose
200
+ const local = readTextIfExists(targetPath);
201
+
202
+ const original = oldRelease.readFile(relPath);
203
+ const status = classify(original, local, '');
204
+
205
+ switch (status) {
206
+ case 'safe-update':
207
+ changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, '', relPath);
208
+ deletedCount++;
209
+ break;
210
+ case 'conflict':
211
+ conflicts.push({
212
+ relPath,
213
+ patchPath: joinPatchPath(TOOLKIT_DIR, relPath),
214
+ original,
215
+ local,
216
+ updated: '',
217
+ removedUpstream: true,
218
+ });
219
+ break;
220
+ // 'unchanged'/'keep-local' can't occur here: original is always
221
+ // non-empty (relPath came from oldRelease.allFiles()) and updated is
222
+ // always '', so upstreamChanged is unconditionally true.
223
+ }
224
+ }
225
+
183
226
  const managedBlockCounts = await mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes, conflicts);
184
227
  updatedCount += managedBlockCounts.updatedCount;
185
228
  keptCount += managedBlockCounts.keptCount;
@@ -230,7 +273,11 @@ export async function mergeCommand(options) {
230
273
  await changes.writeAll(projectRoot);
231
274
  }
232
275
 
233
- p.log.success(`${updatedCount} file(s) updated cleanly, ${keptCount} local edit(s) preserved untouched.`);
276
+ p.log.success(
277
+ `${updatedCount} file(s) updated cleanly, ${keptCount} local edit(s) preserved untouched` +
278
+ (deletedCount > 0 ? `, ${deletedCount} file(s) removed upstream and proposed for deletion` : '') +
279
+ '.'
280
+ );
234
281
  if (conflicts.length > 0) {
235
282
  p.log.warn(
236
283
  `${conflicts.length} conflict(s) — both local and upstream changed:\n` +
@@ -243,6 +290,13 @@ export async function mergeCommand(options) {
243
290
  }
244
291
 
245
292
  function buildConflictNote(conflict) {
293
+ if (conflict.removedUpstream) {
294
+ return (
295
+ `This file was modified locally, but removed upstream in the new version.\n` +
296
+ `Automatic deletion was skipped — review manually or ask your AI assistant:\n` +
297
+ `"reconcile my local changes to ${conflict.relPath}, which was removed upstream"\n`
298
+ );
299
+ }
246
300
  return (
247
301
  `This file was modified locally AND changed upstream.\n` +
248
302
  `Automatic merge was skipped — review manually or ask your AI assistant:\n` +
package/src/lib/github.js CHANGED
@@ -22,6 +22,27 @@ export async function listVersions() {
22
22
  });
23
23
 
24
24
  if (!res.ok) {
25
+ // GitHub's unauthenticated rate limit (60/hr, shared across every caller
26
+ // on the same IP — e.g. a shared CI runner or sandbox) surfaces as a
27
+ // plain 403, indistinguishable from a real auth/network failure unless
28
+ // the response headers are inspected. Left as a generic error, this
29
+ // sends whoever/whatever hits it down a diagnostic path (checking
30
+ // headers, retrying with curl, poking at User-Agent) to rediscover a
31
+ // fix (`toolcrib init --version <x.y.z>`) that already exists and is
32
+ // documented — see CLI README. Checked here so the message states the
33
+ // real cause and the real fix directly, instead of a bare status code.
34
+ const remaining = res.status === 403 ? res.headers?.get?.('x-ratelimit-remaining') : null;
35
+ if (res.status === 403 && remaining === '0') {
36
+ const resetHeader = res.headers?.get?.('x-ratelimit-reset');
37
+ const resetAt = resetHeader ? new Date(Number(resetHeader) * 1000).toLocaleTimeString() : 'unknown';
38
+ throw new Error(
39
+ `GitHub's unauthenticated API rate limit (60 requests/hour, shared by IP) is exhausted — ` +
40
+ `resets around ${resetAt}. This only affects version *discovery* ("latest" resolution); it ` +
41
+ `does not affect release downloads themselves. Fix: run \`toolcrib init --version <x.y.z>\` ` +
42
+ `(or \`apply\`/\`merge\` with an explicit version) with a version you already know, which skips ` +
43
+ `this call entirely.`
44
+ );
45
+ }
25
46
  throw new Error(`Failed to fetch release list: ${res.status} ${res.statusText}`);
26
47
  }
27
48
 
@@ -13,7 +13,13 @@ export function applyPatchFallback(patchPath, projectRoot) {
13
13
  const patchText = fs.readFileSync(patchPath, 'utf-8');
14
14
  const [parsed] = parsePatch(patchText);
15
15
 
16
- const targetRelPath = parsed.newFileName.replace(/^b\//, '');
16
+ const isDeletedFile = parsed.newFileName === '/dev/null';
17
+ // A deletion's real target is its *source* name (oldFileName) — newFileName
18
+ // is /dev/null itself for a deletion, so falling through to the same
19
+ // newFileName-based path resolution used for create/update would target
20
+ // a literal "/dev/null" path inside the project instead of the file
21
+ // actually being removed.
22
+ const targetRelPath = (isDeletedFile ? parsed.oldFileName : parsed.newFileName).replace(/^[ab]\//, '');
17
23
  const targetPath = path.join(projectRoot, targetRelPath);
18
24
 
19
25
  // Defense in depth: every relPath this CLI itself writes into a patch
@@ -31,6 +37,16 @@ export function applyPatchFallback(patchPath, projectRoot) {
31
37
  return { success: false, error: `Refusing to apply patch: target path "${targetRelPath}" resolves outside the project root.` };
32
38
  }
33
39
 
40
+ if (isDeletedFile) {
41
+ if (!fs.existsSync(targetPath)) {
42
+ // Already gone (e.g. a re-run after a partial previous apply) —
43
+ // the end state this patch wants is already true, not a failure.
44
+ return { success: true };
45
+ }
46
+ fs.rmSync(targetPath);
47
+ return { success: true };
48
+ }
49
+
34
50
  const isNewFile = parsed.oldFileName === '/dev/null';
35
51
  const currentContent = isNewFile ? '' : fs.readFileSync(targetPath, 'utf-8');
36
52
 
@@ -62,7 +62,9 @@ export class PendingChanges {
62
62
  * built, regardless of whether the caller already went through
63
63
  * joinPatchPath() or constructed relPath some other way.
64
64
  * @param {string} currentContent - '' if the file doesn't exist yet
65
- * @param {string} proposedContent - the desired final content
65
+ * @param {string} proposedContent - '' to propose deleting the file
66
+ * (only meaningful when currentContent is non-empty — '' vs '' is
67
+ * already a no-op via the check below)
66
68
  * @param {string} [label] - display label for the patch header
67
69
  */
68
70
  propose(relPath, currentContent, proposedContent, label) {
@@ -74,16 +76,25 @@ export class PendingChanges {
74
76
  if (normalize(currentContent) === normalize(proposedContent)) return; // no-op, nothing to propose
75
77
 
76
78
  const isNewFile = currentContent === '';
79
+ // Symmetric with isNewFile above: a deletion is just a patch whose
80
+ // *target* is /dev/null instead of its *source* — git apply (confirmed
81
+ // directly against a real repo, not assumed) recognizes this from a
82
+ // plain unified diff exactly the same way it recognizes a new file from
83
+ // an empty source, no git-extended `diff --git`/`deleted file mode`
84
+ // headers required. The `!isNewFile` guard only rules out the
85
+ // '' -> '' case, already caught by the no-op check above; kept for
86
+ // clarity that a file can't be simultaneously new and deleted.
87
+ const isDeletedFile = proposedContent === '' && !isNewFile;
77
88
  const patch = createTwoFilesPatch(
78
89
  isNewFile ? '/dev/null' : `a/${relPath}`,
79
- `b/${relPath}`,
90
+ isDeletedFile ? '/dev/null' : `b/${relPath}`,
80
91
  currentContent,
81
92
  proposedContent,
82
93
  isNewFile ? undefined : `${label} (current)`,
83
- isNewFile ? `${label} (new file)` : `${label} (proposed)`
94
+ isDeletedFile ? undefined : isNewFile ? `${label} (new file)` : `${label} (proposed)`
84
95
  );
85
96
 
86
- this.entries.push({ relPath, patch, isNewFile });
97
+ this.entries.push({ relPath, patch, isNewFile, isDeletedFile });
87
98
  }
88
99
 
89
100
  isEmpty() {
@@ -96,7 +107,7 @@ export class PendingChanges {
96
107
 
97
108
  summarize() {
98
109
  return this.entries
99
- .map((e) => ` ${e.isNewFile ? '+ (new) ' : '~ '}${e.relPath}`)
110
+ .map((e) => ` ${e.isDeletedFile ? '- (deleted) ' : e.isNewFile ? '+ (new) ' : '~ '}${e.relPath}`)
100
111
  .join('\n');
101
112
  }
102
113
 
@@ -0,0 +1,88 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ // Directories never worth descending into for this scan: dependency trees,
5
+ // VCS internals, build output, and the vendored toolkit itself (its own
6
+ // source legitimately contains `<ThemeProvider>`/`<ToastProvider>` --
7
+ // scanning it would produce a false "found it" even for a consumer who
8
+ // never wired their own root).
9
+ const EXCLUDED_DIR_NAMES = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'toolcrib']);
10
+ const SOURCE_FILE_PATTERN = /\.(tsx|jsx|ts|js)$/;
11
+ // A generous but bounded walk -- this is a best-effort heuristic diagnostic
12
+ // (grep for a JSX pattern), not the byte-exact vendored-file drift check
13
+ // elsewhere in this tool, so it deliberately stops rather than walking an
14
+ // unbounded tree on a pathological repo layout.
15
+ const MAX_FILES_SCANNED = 2000;
16
+
17
+ function listCandidateFiles(rootDir) {
18
+ const results = [];
19
+ const stack = [rootDir];
20
+ while (stack.length > 0 && results.length < MAX_FILES_SCANNED) {
21
+ const dir = stack.pop();
22
+ let entries;
23
+ try {
24
+ entries = fs.readdirSync(dir, { withFileTypes: true });
25
+ } catch {
26
+ continue; // unreadable directory (permissions, symlink loop) -- skip, not fatal to the scan
27
+ }
28
+ for (const entry of entries) {
29
+ if (entry.isDirectory()) {
30
+ if (EXCLUDED_DIR_NAMES.has(entry.name) || entry.name.startsWith('.')) continue;
31
+ stack.push(path.join(dir, entry.name));
32
+ } else if (SOURCE_FILE_PATTERN.test(entry.name)) {
33
+ results.push(path.join(dir, entry.name));
34
+ }
35
+ }
36
+ }
37
+ return results;
38
+ }
39
+
40
+ /**
41
+ * Read-only heuristic: does this project's own source wire up toolcrib's
42
+ * root providers, via `<ToolcribProvider>` or the equivalent manual
43
+ * `<ThemeProvider>` + `<ToastProvider>` + `<ToastContainer>` composition?
44
+ * Both are legitimate per `CORE.md` §1 -- this doesn't prefer one, it just
45
+ * confirms *something* is wired, since every toolcrib component throws or
46
+ * silently no-ops without it, and that failure mode gives no clue back to
47
+ * "you forgot the root setup."
48
+ *
49
+ * Necessarily a grep-style heuristic, not a real JSX/AST check (unlike the
50
+ * byte-exact vendored-file drift check elsewhere in this tool) -- a false
51
+ * positive (e.g. these strings appearing only in a comment) is judged the
52
+ * safer failure mode than a false "not found" nagging a project that's
53
+ * actually wired correctly, just not in a way this scan happens to expect
54
+ * (e.g. `ThemeProvider` re-exported under a local alias).
55
+ *
56
+ * Scans from `<projectRoot>/src` if present (the near-universal convention
57
+ * for a React app's own source), falling back to `projectRoot` itself for
58
+ * a project with no `src/` directory. Returns `{ found: boolean, via:
59
+ * 'ToolcribProvider' | 'manual' | null }`.
60
+ */
61
+ export function checkRootProviderWired(projectRoot) {
62
+ const scanRoot = fs.existsSync(path.join(projectRoot, 'src')) ? path.join(projectRoot, 'src') : projectRoot;
63
+ if (!fs.existsSync(scanRoot)) return { found: false, via: null };
64
+
65
+ let sawThemeProvider = false;
66
+ let sawToastProvider = false;
67
+ let sawToastContainer = false;
68
+
69
+ for (const filePath of listCandidateFiles(scanRoot)) {
70
+ let text;
71
+ try {
72
+ text = fs.readFileSync(filePath, 'utf-8');
73
+ } catch {
74
+ continue;
75
+ }
76
+ if (text.includes('<ToolcribProvider')) {
77
+ return { found: true, via: 'ToolcribProvider' };
78
+ }
79
+ if (text.includes('<ThemeProvider')) sawThemeProvider = true;
80
+ if (text.includes('<ToastProvider')) sawToastProvider = true;
81
+ if (text.includes('<ToastContainer')) sawToastContainer = true;
82
+ }
83
+
84
+ if (sawThemeProvider && sawToastProvider && sawToastContainer) {
85
+ return { found: true, via: 'manual' };
86
+ }
87
+ return { found: false, via: null };
88
+ }