@jondeodat/claude-setup-cli 0.0.0-stage → 0.2.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jon Deodat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,159 @@
1
- # Temporary Holding Version
1
+ # claude-setup
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sets up, at project scope, the Claude Code marketplaces and plugins that a project declares in its
4
+ `.claude/settings.json`, so that a project does not depend on what each developer configured.
5
+
6
+ Claude Code does not do it on its own: a marketplace declared in `extraKnownMarketplaces` is unknown to
7
+ the `claude` CLI until a session has run in the trusted folder, and a plugin enabled in `enabledPlugins`
8
+ only loads once installed on the developer's machine, once per clone.
9
+
10
+ ## What it does
11
+
12
+ Run from the root of a project, it:
13
+
14
+ 1. registers each marketplace of `extraKnownMarketplaces` that the machine does not know yet:
15
+ `claude plugin marketplace add <source> --scope project`;
16
+ 2. installs each plugin set to `true` in `enabledPlugins` that no installation covers for this clone:
17
+ `claude plugin install <plugin> --scope project`. A user installation counts, a project or local
18
+ one only in the clone it was made in;
19
+ 3. refreshes the marketplaces the project declares, then:
20
+ - updates at once the plugins of those declared with `"autoUpdate": true`, in the scope they were
21
+ installed in;
22
+ - updates the plugins of the others once their new version is older than the project's
23
+ `min-release-age`, the delay the project already imposes on npm packages (see below);
24
+ 4. puts `.claude/settings.json` back as it found it: the `claude` CLI rewrites the whole file in its own
25
+ format on an add or an install, and `marketplace add` even drops the `autoUpdate` of an existing entry.
26
+
27
+ It reports what it did, and that a running session needs `/reload-plugins` to use an installed or
28
+ updated plugin.
29
+
30
+ ### The release-age delay
31
+
32
+ A marketplace without `autoUpdate` is one the project does not control, a third-party one: its new
33
+ versions wait like npm packages do. The delay is the `min-release-age` that npm reads from the project
34
+ (`npm config get min-release-age` at its root, so the project's `.npmrc` unless an environment variable
35
+ overrides it); without one, updates apply at once.
36
+
37
+ A marketplace clone is shallow, so the commit that introduced a version is out of reach. The release date
38
+ is estimated as the earlier of the day `claude-setup` first saw the version and the date of the last
39
+ commit of the clone: both come after the release, so the delay is never shortened, at worst lengthened.
40
+ A held-back version is reported once, with the day it will apply; the first sightings are recorded in
41
+ `node_modules/.cache/claude-setup/state.json`.
42
+
43
+ It never fails, so that it cannot break an `npm install` or a session start: a failure (network down,
44
+ unknown plugin…) is reported, and the run goes on. It does nothing without the `claude` CLI, in CI (`CI`
45
+ set), or with `CLAUDE_SETUP_SKIP` set.
46
+
47
+ The `claude` CLI it runs is the one `CLAUDE_CODE_EXECPATH` names, or else the `claude` on the `PATH`,
48
+ whichever first answers `--version` as Claude Code. Claude Code sets `CLAUDE_CODE_EXECPATH` in the
49
+ processes it starts, a hook among them: a Claude Code installed only as an IDE extension puts no `claude`
50
+ on the `PATH`, but names its own binary in the variable, so its hooks still find it. The variable is not
51
+ documented, and may name a binary an update removed since or one that is not the `claude` CLI, hence the
52
+ check and the fallback.
53
+
54
+ ## Installation
55
+
56
+ ```sh
57
+ npm install --save-dev --save-exact @jondeodat/claude-setup-cli
58
+ ```
59
+
60
+ It needs Node 22 or later, and has no dependencies: the package ships its TypeScript sources compiled to
61
+ JavaScript.
62
+
63
+ ## Usage
64
+
65
+ ```sh
66
+ claude-setup [--hook] [--max-age <hours>]
67
+ ```
68
+
69
+ - `--hook` prints its report as the JSON output of a `SessionStart` hook, and nothing when there is nothing
70
+ to report. The terminal shows its `systemMessage`, in yellow; the IDE extensions do not show it, so an
71
+ `additionalContext` asks Claude to pass the news on at the start of its first reply.
72
+ - `--max-age <hours>` refreshes the marketplaces only when the last refresh, recorded in
73
+ `node_modules/.cache/claude-setup/state.json`, is older. Without it, every run refreshes.
74
+
75
+ In a project, from a `SessionStart` hook of `.claude/settings.json`, once a day. The guard skips it in a
76
+ clone where the dependencies are not installed yet:
77
+
78
+ ```json
79
+ "hooks": {
80
+ "SessionStart": [
81
+ {
82
+ "matcher": "startup",
83
+ "hooks": [
84
+ {
85
+ "type": "command",
86
+ "command": "cd \"$CLAUDE_PROJECT_DIR\" && [ -x node_modules/.bin/claude-setup ] && node_modules/.bin/claude-setup --hook --max-age 24 || true"
87
+ }
88
+ ]
89
+ }
90
+ ]
91
+ }
92
+ ```
93
+
94
+ Optionally, also from the `prepare` script of its `package.json`, which runs on an `npm install` or
95
+ `npm ci` in the project itself but not where the project is installed as a dependency (unlike
96
+ `postinstall`):
97
+
98
+ ```json
99
+ "prepare": "claude-setup"
100
+ ```
101
+
102
+ - npm does not run it when `ignore-scripts` is set, a common hardening: `ignore-scripts` turns off the
103
+ scripts of the project's own `package.json` too, and `allowScripts` cannot let it through, since it only
104
+ covers the install scripts of dependencies and `ignore-scripts` overrides it. `npm run prepare` still
105
+ runs it.
106
+ - Run by npm, it only has `CLAUDE_CODE_EXECPATH` when the `npm install` itself was started from Claude
107
+ Code, such as from its Bash tool: otherwise it needs `claude` on the `PATH`.
108
+
109
+ ## Development
110
+
111
+ ```sh
112
+ npm ci
113
+ npm test # Vitest
114
+ npm run typecheck # tsc: Node strips the types without checking them
115
+ npm run build # tsc -p tsconfig.build.json: compiles to dist/, what the package ships
116
+ npm run format:check # Prettier
117
+ ```
118
+
119
+ Node runs the TypeScript sources directly, by stripping their types (`npm start`, the CLI tests). It needs
120
+ Node 22.18 or later: the `devEngines` of `package.json` makes older ones refuse to install.
121
+ `erasableSyntaxOnly` in `tsconfig.json` keeps out the syntax Node cannot strip (`enum`, `namespace`…), and
122
+ the relative imports name the `.ts` file, which `tsc` rewrites to `.js` in `dist/`. Node refuses to strip
123
+ the types of a file under `node_modules`, hence the compiled package.
124
+
125
+ ### Dependency install scripts
126
+
127
+ The install scripts of a dependency (`preinstall`, `install`, `postinstall`) run any code on the machine
128
+ at install time, the usual entry point of supply chain attacks. `.npmrc` sets `strict-allow-scripts=true`:
129
+ npm only runs the scripts approved in the `allowScripts` field of `package.json`, skips the denied ones,
130
+ and fails the install on a dependency it has not been told about. Both need npm 11.20 or later, older ones
131
+ ignore them and run every script: the `devEngines` of `package.json` makes them refuse to install instead.
132
+ Read the script first, then record the decision:
133
+
134
+ ```sh
135
+ npm install-scripts approve <pkg> # pinned to the reviewed version: approve again after a bump
136
+ npm install-scripts deny <pkg>
137
+ ```
138
+
139
+ No dependency has an install script at the moment: `allowScripts` is empty.
140
+
141
+ `.npmrc` also sets `min-release-age=7`: npm installs no version published less than 7 days ago.
142
+
143
+ ## Publish process
144
+
145
+ Bump the version, then publish on npm:
146
+
147
+ ```sh
148
+ npm version <patch|minor|major> --no-git-tag-version
149
+ npm run push
150
+ ```
151
+
152
+ - `npm version` only updates `package.json` and `package-lock.json`: commit them with the change they ship.
153
+ - `npm run push` runs `npm publish`, whose `prepublishOnly` script first runs `npm run typecheck`,
154
+ `npm test`, `npm run format:check` and `npm run build`, and stops if one fails; then it publishes the
155
+ package, publicly, on registry.npmjs.org.
156
+
157
+ ## License
158
+
159
+ [MIT](LICENSE)
@@ -0,0 +1,312 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'child_process';
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
4
+ import { dirname, join } from 'path';
5
+ import { parseArgs } from 'util';
6
+ import { createReport, estimateReleasedAt, findInstallation, findOfferedVersion, findUpdates, formatHookOutput, formatLines, getAppliesAt, getEnabledPlugins, getMarketplaceArgument, isRefreshDue, parseJsonOutput, parsePluginId, parseReleaseAgeDays, } from "./claude-setup.js";
7
+ const USAGE = `Usage: claude-setup [--hook] [--max-age <hours>]
8
+
9
+ From the root of a project, registers the Claude Code marketplaces and installs the plugins that its
10
+ .claude/settings.json declares, at project scope. Then refreshes those marketplaces: updates the plugins
11
+ of the ones declared with autoUpdate at once, and those of the others once their new version is older
12
+ than the min-release-age npm reads for the project (.npmrc).
13
+
14
+ The claude CLI rewrites .claude/settings.json in its own format: this tool puts the file back as it was.
15
+ It does nothing in CI (CI set), with CLAUDE_SETUP_SKIP set, or without the claude CLI, and never fails.
16
+
17
+ Options:
18
+ --hook prints its report as the JSON output of a SessionStart hook, and nothing when there
19
+ is nothing to report
20
+ --max-age <hours> refreshes the marketplaces only when the last refresh is older (default: every run)
21
+ -h, --help prints this help`;
22
+ /**
23
+ * A `claude plugin` command can clone a marketplace
24
+ */
25
+ const CLAUDE_TIMEOUT_MS = 180_000;
26
+ /**
27
+ * Runs `claude <args> --json` from the project root
28
+ */
29
+ function runClaude(root, args) {
30
+ const child = spawnSync('claude', [...args, '--json'], { cwd: root, encoding: 'utf8', timeout: CLAUDE_TIMEOUT_MS });
31
+ if (child.error) {
32
+ return { error: `claude ${args.join(' ')}: ${child.error.message}` };
33
+ }
34
+ const output = parseJsonOutput(child.stdout);
35
+ const outcome = output?.outcome;
36
+ if (child.status !== 0 || (outcome !== undefined && outcome !== 'ok')) {
37
+ const message = output?.message;
38
+ const reason = typeof message === 'string' ? message : child.stderr.trim() || `exit code ${child.status}`;
39
+ return { output, error: `claude ${args.join(' ')}: ${reason}` };
40
+ }
41
+ return { output };
42
+ }
43
+ function asArray(output) {
44
+ return Array.isArray(output) ? output : [];
45
+ }
46
+ function readJson(path) {
47
+ try {
48
+ return JSON.parse(readFileSync(path, 'utf8'));
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ }
54
+ /**
55
+ * Registers the marketplaces the project declares and that the machine does not know yet, and returns
56
+ * the names of the marketplaces known after that
57
+ */
58
+ function registerMarketplaces(root, settings, report) {
59
+ const listing = runClaude(root, ['plugin', 'marketplace', 'list']);
60
+ if (listing.error) {
61
+ report.failures.push(listing.error);
62
+ return undefined;
63
+ }
64
+ const known = new Set(asArray(listing.output).map(({ name }) => name));
65
+ for (const [name, { source }] of Object.entries(settings.extraKnownMarketplaces ?? {})) {
66
+ if (known.has(name)) {
67
+ continue;
68
+ }
69
+ const argument = getMarketplaceArgument(source);
70
+ if (!argument) {
71
+ report.failures.push(`marketplace ${name}: source "${source.source}" not supported`);
72
+ continue;
73
+ }
74
+ const added = runClaude(root, ['plugin', 'marketplace', 'add', argument, '--scope', 'project']);
75
+ if (added.error) {
76
+ report.failures.push(added.error);
77
+ continue;
78
+ }
79
+ known.add(name);
80
+ report.addedMarketplaces.push(name);
81
+ }
82
+ return known;
83
+ }
84
+ function listInstalledPlugins(root, report) {
85
+ const listing = runClaude(root, ['plugin', 'list']);
86
+ if (listing.error) {
87
+ report.failures.push(listing.error);
88
+ }
89
+ return asArray(listing.output);
90
+ }
91
+ /**
92
+ * Installs, at project scope, the enabled plugins that no installation covers for this project
93
+ */
94
+ function installPlugins(root, settings, known, report) {
95
+ const installedBefore = listInstalledPlugins(root, report);
96
+ const newIds = [];
97
+ for (const id of getEnabledPlugins(settings)) {
98
+ if (findInstallation(installedBefore, id, root)) {
99
+ continue;
100
+ }
101
+ const { marketplace } = parsePluginId(id);
102
+ if (!known.has(marketplace)) {
103
+ report.failures.push(`plugin ${id}: marketplace ${marketplace} is not registered`);
104
+ continue;
105
+ }
106
+ const installation = runClaude(root, ['plugin', 'install', id, '--scope', 'project']);
107
+ if (installation.error) {
108
+ report.failures.push(installation.error);
109
+ continue;
110
+ }
111
+ newIds.push(id);
112
+ }
113
+ if (newIds.length === 0) {
114
+ return installedBefore;
115
+ }
116
+ const installedAfter = listInstalledPlugins(root, report);
117
+ for (const id of newIds) {
118
+ report.installed.push({ id, version: findInstallation(installedAfter, id, root)?.version });
119
+ }
120
+ return installedAfter;
121
+ }
122
+ /**
123
+ * The project's minimum release age, in days, as npm resolves it from its .npmrc files and environment
124
+ */
125
+ function readReleaseAgeDays(root) {
126
+ const child = spawnSync('npm', ['config', 'get', 'min-release-age'], { cwd: root, encoding: 'utf8' });
127
+ return child.error || child.status !== 0 ? 0 : parseReleaseAgeDays(child.stdout);
128
+ }
129
+ /**
130
+ * When the last commit of a marketplace clone was made, or undefined if git cannot tell
131
+ */
132
+ function readLastCommittedAt(location) {
133
+ const child = spawnSync('git', ['-C', location, 'log', '-1', '--format=%ct'], { encoding: 'utf8' });
134
+ const seconds = Number(child.stdout?.trim());
135
+ return child.status === 0 && seconds > 0 ? seconds * 1000 : undefined;
136
+ }
137
+ /**
138
+ * Updates a plugin. The change is reported from the listings around the refresh, not from this
139
+ * command's output: see findUpdates.
140
+ */
141
+ function update(root, id, scope, report) {
142
+ const result = runClaude(root, ['plugin', 'update', id, '--scope', scope]);
143
+ if (result.error) {
144
+ report.failures.push(result.error);
145
+ }
146
+ }
147
+ /**
148
+ * Refreshes the marketplaces the project declares, updates the plugins of the ones declared with
149
+ * autoUpdate, and the plugins of the others once their new version is older than the project's
150
+ * min-release-age. `installedBefore` lists the installations before the refresh. Returns when each
151
+ * version still held back was first seen.
152
+ */
153
+ function refresh(root, settings, known, installedBefore, state, now, report) {
154
+ const declared = settings.extraKnownMarketplaces ?? {};
155
+ for (const name of Object.keys(declared)) {
156
+ if (!known.has(name)) {
157
+ continue;
158
+ }
159
+ const update = runClaude(root, ['plugin', 'marketplace', 'update', name]);
160
+ if (update.error) {
161
+ report.failures.push(update.error);
162
+ }
163
+ }
164
+ const locations = new Map(asArray(runClaude(root, ['plugin', 'marketplace', 'list']).output).map(({ name, installLocation }) => [name, installLocation]));
165
+ const installed = listInstalledPlugins(root, report);
166
+ const justInstalled = new Set(report.installed.map(({ id }) => id));
167
+ const minAgeDays = readReleaseAgeDays(root);
168
+ const firstSeen = {};
169
+ const enabledIds = getEnabledPlugins(settings);
170
+ let hasRunUpdate = false;
171
+ for (const id of enabledIds) {
172
+ const installation = findInstallation(installed, id, root);
173
+ const { name, marketplace } = parsePluginId(id);
174
+ const declaration = declared[marketplace];
175
+ if (!installation || !declaration || justInstalled.has(id)) {
176
+ continue;
177
+ }
178
+ if (declaration.autoUpdate) {
179
+ update(root, id, installation.scope, report);
180
+ hasRunUpdate = true;
181
+ continue;
182
+ }
183
+ const location = locations.get(marketplace);
184
+ if (!location) {
185
+ continue;
186
+ }
187
+ const catalog = readJson(join(location, '.claude-plugin', 'marketplace.json'));
188
+ const offered = catalog && findOfferedVersion(catalog, name, (path) => readJson(join(location, path, '.claude-plugin', 'plugin.json'))?.version);
189
+ if (!offered || !installation.version || offered === installation.version) {
190
+ continue;
191
+ }
192
+ const key = `${id} ${offered}`;
193
+ const firstSeenAt = state.firstSeen?.[key] ?? now;
194
+ const appliesAt = getAppliesAt(estimateReleasedAt(firstSeenAt, readLastCommittedAt(location)), minAgeDays);
195
+ if (now >= appliesAt) {
196
+ update(root, id, installation.scope, report);
197
+ hasRunUpdate = true;
198
+ continue;
199
+ }
200
+ firstSeen[key] = firstSeenAt;
201
+ if (state.firstSeen?.[key] === undefined) {
202
+ report.pending.push({ id, from: installation.version, to: offered, appliesOn: new Date(appliesAt).toISOString().slice(0, 10) });
203
+ }
204
+ }
205
+ const installedAfter = hasRunUpdate ? listInstalledPlugins(root, report) : installed;
206
+ report.updated.push(...findUpdates(installedBefore, installedAfter, enabledIds, root));
207
+ return firstSeen;
208
+ }
209
+ function readState(path) {
210
+ return readJson(path) ?? {};
211
+ }
212
+ function writeState(path, state) {
213
+ try {
214
+ mkdirSync(dirname(path), { recursive: true });
215
+ writeFileSync(path, JSON.stringify(state));
216
+ }
217
+ catch {
218
+ // Without a state, the next run refreshes again and restarts the delays: nothing worse
219
+ }
220
+ }
221
+ function setUp(root, settings, maxAgeHours, report) {
222
+ const known = registerMarketplaces(root, settings, report);
223
+ if (!known) {
224
+ return;
225
+ }
226
+ const installed = installPlugins(root, settings, known, report);
227
+ const statePath = join(root, 'node_modules', '.cache', 'claude-setup', 'state.json');
228
+ const state = readState(statePath);
229
+ const now = Date.now();
230
+ if (isRefreshDue(state.refreshedAt, now, maxAgeHours)) {
231
+ const firstSeen = refresh(root, settings, known, installed, state, now, report);
232
+ writeState(statePath, { refreshedAt: now, firstSeen });
233
+ }
234
+ }
235
+ function print(report, isHook) {
236
+ if (isHook) {
237
+ const output = formatHookOutput(report);
238
+ if (output) {
239
+ console.log(output);
240
+ }
241
+ return;
242
+ }
243
+ for (const line of formatLines(report)) {
244
+ (line.startsWith('failed:') ? console.error : console.log)(`claude-setup: ${line}`);
245
+ }
246
+ }
247
+ function parseOptions() {
248
+ try {
249
+ return parseArgs({
250
+ options: {
251
+ hook: { type: 'boolean' },
252
+ 'max-age': { type: 'string' },
253
+ help: { type: 'boolean', short: 'h' },
254
+ },
255
+ }).values;
256
+ }
257
+ catch (error) {
258
+ console.error(`claude-setup: ${error instanceof Error ? error.message : String(error)}\n\n${USAGE}`);
259
+ process.exitCode = 1;
260
+ return undefined;
261
+ }
262
+ }
263
+ function main() {
264
+ const values = parseOptions();
265
+ if (!values) {
266
+ return;
267
+ }
268
+ if (values.help) {
269
+ console.log(USAGE);
270
+ return;
271
+ }
272
+ const maxAgeHours = values['max-age'] === undefined ? undefined : Number(values['max-age']);
273
+ if (maxAgeHours !== undefined && !(maxAgeHours >= 0)) {
274
+ console.error(`claude-setup: --max-age expects a number of hours\n\n${USAGE}`);
275
+ process.exitCode = 1;
276
+ return;
277
+ }
278
+ if (process.env.CI || process.env.CLAUDE_SETUP_SKIP) {
279
+ return;
280
+ }
281
+ const root = process.cwd();
282
+ const settingsPath = join(root, '.claude', 'settings.json');
283
+ if (!existsSync(settingsPath)) {
284
+ return;
285
+ }
286
+ const isHook = values.hook === true;
287
+ const report = createReport();
288
+ const original = readFileSync(settingsPath, 'utf8');
289
+ try {
290
+ const probe = spawnSync('claude', ['--version'], { encoding: 'utf8' });
291
+ if (probe.error) {
292
+ return;
293
+ }
294
+ setUp(root, JSON.parse(original), maxAgeHours, report);
295
+ }
296
+ catch (error) {
297
+ report.failures.push(error instanceof Error ? error.message : String(error));
298
+ }
299
+ finally {
300
+ if (readFileSync(settingsPath, 'utf8') !== original) {
301
+ writeFileSync(settingsPath, original);
302
+ }
303
+ }
304
+ print(report, isHook);
305
+ }
306
+ try {
307
+ main();
308
+ }
309
+ catch (error) {
310
+ // Never fail the npm install or the session start that runs this tool
311
+ console.error(`claude-setup: ${error instanceof Error ? error.message : String(error)}`);
312
+ }
@@ -0,0 +1,195 @@
1
+ export function createReport() {
2
+ return { addedMarketplaces: [], installed: [], updated: [], pending: [], failures: [] };
3
+ }
4
+ const DAY_MS = 86_400_000;
5
+ /**
6
+ * The minimum release age, in days, from the output of `npm config get min-release-age`: 0 when npm
7
+ * sets none (`null`)
8
+ */
9
+ export function parseReleaseAgeDays(npmOutput) {
10
+ const days = Number(npmOutput.trim());
11
+ return Number.isFinite(days) && days > 0 ? days : 0;
12
+ }
13
+ /**
14
+ * When the version a marketplace offers was released, at the latest. Its clone is shallow, so the
15
+ * commit that introduced the version is out of reach; both the day this tool first saw the version and
16
+ * the date of the last commit of the clone come after that release, so the earlier of the two never
17
+ * shortens the delay.
18
+ */
19
+ export function estimateReleasedAt(firstSeenAt, lastCommittedAt) {
20
+ return lastCommittedAt === undefined ? firstSeenAt : Math.min(firstSeenAt, lastCommittedAt);
21
+ }
22
+ /**
23
+ * When a version released at `releasedAt` may be applied, given the minimum release age in days
24
+ */
25
+ export function getAppliesAt(releasedAt, minAgeDays) {
26
+ return releasedAt + minAgeDays * DAY_MS;
27
+ }
28
+ /**
29
+ * The argument `claude plugin marketplace add` takes for a source, or undefined for a source it cannot add
30
+ */
31
+ export function getMarketplaceArgument(source) {
32
+ switch (source.source) {
33
+ case 'github':
34
+ return source.repo;
35
+ case 'git':
36
+ case 'url':
37
+ return source.url;
38
+ case 'directory':
39
+ case 'file':
40
+ return source.path;
41
+ default:
42
+ return undefined;
43
+ }
44
+ }
45
+ /**
46
+ * The ids (`plugin@marketplace`) of the plugins the project enables
47
+ */
48
+ export function getEnabledPlugins(settings) {
49
+ return Object.entries(settings.enabledPlugins ?? {})
50
+ .filter(([, isEnabled]) => isEnabled === true)
51
+ .map(([id]) => id);
52
+ }
53
+ /**
54
+ * Splits a plugin id `plugin@marketplace` into its two names
55
+ */
56
+ export function parsePluginId(id) {
57
+ const at = id.lastIndexOf('@');
58
+ return at > 0 ? { name: id.slice(0, at), marketplace: id.slice(at + 1) } : { name: id, marketplace: '' };
59
+ }
60
+ /**
61
+ * The installation of a plugin that applies to the project at `root`: a user or managed one applies
62
+ * everywhere, a project or local one only to the clone it was made in
63
+ */
64
+ export function findInstallation(plugins, id, root) {
65
+ return plugins.find((plugin) => plugin.id === id && (plugin.scope === 'user' || plugin.scope === 'managed' || plugin.projectPath === root));
66
+ }
67
+ function parseJson(text) {
68
+ try {
69
+ return JSON.parse(text);
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ }
75
+ /**
76
+ * The plugins among `ids` whose installation for the project at `root` changed version between two
77
+ * listings. Comparing listings catches an update whichever command applied it: `claude plugin
78
+ * marketplace update` already updates the plugins of an autoUpdate marketplace when it pulls new
79
+ * commits, and the `plugin update` that follows then reports no change.
80
+ */
81
+ export function findUpdates(before, after, ids, root) {
82
+ return ids.flatMap((id) => {
83
+ const from = findInstallation(before, id, root)?.version;
84
+ const to = findInstallation(after, id, root)?.version;
85
+ return from && to && from !== to ? [{ id, from, to }] : [];
86
+ });
87
+ }
88
+ /**
89
+ * The JSON output of a `claude plugin … --json` command: the whole standard output for a listing, which
90
+ * spans several lines, or else its last non-empty line, which an action prints after its progress
91
+ */
92
+ export function parseJsonOutput(stdout) {
93
+ const whole = parseJson(stdout.trim());
94
+ if (whole !== undefined) {
95
+ return whole;
96
+ }
97
+ const lastLine = stdout
98
+ .split('\n')
99
+ .map((line) => line.trim())
100
+ .filter(Boolean)
101
+ .at(-1);
102
+ return lastLine ? parseJson(lastLine) : undefined;
103
+ }
104
+ /**
105
+ * Whether the marketplaces should be refreshed: always without a maximum age, otherwise once the last
106
+ * refresh is older than it
107
+ */
108
+ export function isRefreshDue(lastRefreshedAt, now, maxAgeHours) {
109
+ if (maxAgeHours === undefined || lastRefreshedAt === undefined) {
110
+ return true;
111
+ }
112
+ return now - lastRefreshedAt >= maxAgeHours * 3_600_000;
113
+ }
114
+ /**
115
+ * The version a marketplace offers for a plugin: the `version` of its entry in `marketplace.json`, or
116
+ * else the one of the `plugin.json` its relative source points to. Undefined when neither gives one.
117
+ */
118
+ export function findOfferedVersion(marketplace, pluginName, readPluginVersion) {
119
+ const entry = marketplace.plugins?.find((plugin) => plugin.name === pluginName);
120
+ if (!entry) {
121
+ return undefined;
122
+ }
123
+ if (entry.version) {
124
+ return entry.version;
125
+ }
126
+ return typeof entry.source === 'string' ? readPluginVersion(entry.source) : undefined;
127
+ }
128
+ /**
129
+ * Whether the run changed the plugins the current session loaded, which then need a reload
130
+ */
131
+ export function needsReload(report) {
132
+ return report.installed.length > 0 || report.updated.length > 0;
133
+ }
134
+ function describeChange({ id, from, to }) {
135
+ return `${id} ${from ?? '?'} → ${to ?? '?'}`;
136
+ }
137
+ /**
138
+ * The lines that report a run on the console, empty when there is nothing to report
139
+ */
140
+ export function formatLines(report) {
141
+ const lines = [];
142
+ for (const name of report.addedMarketplaces) {
143
+ lines.push(`marketplace registered: ${name}`);
144
+ }
145
+ for (const { id, version } of report.installed) {
146
+ lines.push(`plugin installed: ${id} ${version ?? ''}`.trimEnd());
147
+ }
148
+ for (const change of report.updated) {
149
+ lines.push(`plugin updated: ${describeChange(change)}`);
150
+ }
151
+ for (const change of report.pending) {
152
+ lines.push(`plugin update held back by min-release-age: ${describeChange(change)}, applied from ${change.appliesOn}`);
153
+ }
154
+ if (needsReload(report)) {
155
+ lines.push('run /reload-plugins in a running Claude Code session, or start a new one');
156
+ }
157
+ for (const failure of report.failures) {
158
+ lines.push(`failed: ${failure}`);
159
+ }
160
+ return lines;
161
+ }
162
+ const YELLOW = '\u001b[33m';
163
+ const RESET = '\u001b[0m';
164
+ /**
165
+ * The JSON a SessionStart hook prints to report a run, or undefined when there is nothing to report.
166
+ * The terminal shows `systemMessage`, the IDE extensions do not: there, `additionalContext` asks
167
+ * Claude to pass the news on in its first reply.
168
+ */
169
+ export function formatHookOutput(report) {
170
+ const lines = formatLines(report);
171
+ if (lines.length === 0) {
172
+ return undefined;
173
+ }
174
+ const output = {
175
+ systemMessage: `${YELLOW}claude-setup: ${lines.join('\n')}${RESET}`,
176
+ };
177
+ const news = [];
178
+ if (needsReload(report)) {
179
+ const changes = [...report.installed.map(({ id, version }) => `${id} ${version ?? ''}`.trimEnd()), ...report.updated.map(describeChange)];
180
+ news.push(`The claude-setup hook installed or updated these Claude Code plugins for this project: ${changes.join(', ')}. ` +
181
+ 'This session still runs the plugins it loaded before: the developer must run /reload-plugins or start a new session.');
182
+ }
183
+ if (report.pending.length > 0) {
184
+ news.push("New versions of these Claude Code plugins are held back by the project's min-release-age, and will be applied automatically: " +
185
+ report.pending.map((change) => `${describeChange(change)} from ${change.appliesOn}`).join(', ') +
186
+ '.');
187
+ }
188
+ if (news.length > 0) {
189
+ output.hookSpecificOutput = {
190
+ hookEventName: 'SessionStart',
191
+ additionalContext: `${news.join(' ')} At the start of your first reply, tell the developer this in one or two short sentences, in their language, whatever they asked.`,
192
+ };
193
+ }
194
+ return JSON.stringify(output);
195
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@jondeodat/claude-setup-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Registers the Claude Code marketplaces and installs the plugins that a project declares in .claude/settings.json, at project scope.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "author": "Jon Deodat <deodatamadeus@gmail.com>",
8
+ "homepage": "https://github.com/jondeodat/claude-setup-cli#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/jondeodat/claude-setup-cli.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/jondeodat/claude-setup-cli/issues"
15
+ },
16
+ "bin": {
17
+ "claude-setup": "dist/claude-setup-cli.js"
18
+ },
19
+ "files": [
20
+ "dist/claude-setup.js",
21
+ "dist/claude-setup-cli.js"
22
+ ],
23
+ "publishConfig": {
24
+ "registry": "https://registry.npmjs.org/",
25
+ "access": "public"
26
+ },
27
+ "engines": {
28
+ "node": ">=22"
29
+ },
30
+ "devEngines": {
31
+ "runtime": {
32
+ "name": "node",
33
+ "version": ">=22.18.0",
34
+ "onFail": "error"
35
+ },
36
+ "packageManager": {
37
+ "name": "npm",
38
+ "version": ">=11.20.0",
39
+ "onFail": "error"
40
+ }
41
+ },
42
+ "scripts": {
43
+ "start": "node claude-setup-cli.ts",
44
+ "build": "tsc -p tsconfig.build.json",
45
+ "typecheck": "tsc",
46
+ "test": "vitest run",
47
+ "format": "prettier --write .",
48
+ "format:check": "prettier --check .",
49
+ "prepublishOnly": "npm run typecheck && npm test && npm run format:check && npm run build",
50
+ "push": "npm publish"
51
+ },
52
+ "keywords": [
53
+ "claude",
54
+ "claude-code",
55
+ "plugin",
56
+ "marketplace",
57
+ "setup"
58
+ ],
59
+ "devDependencies": {
60
+ "@types/node": "24.19.0",
61
+ "prettier": "3.9.9",
62
+ "typescript": "5.9.3",
63
+ "vite": "8.3.3",
64
+ "vitest": "5.0.3"
65
+ },
66
+ "allowScripts": {}
67
+ }