dsh-plugin-toolkit 0.20.12 → 0.20.13

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/lib/dev.mjs CHANGED
@@ -13,16 +13,18 @@ import path from 'node:path';
13
13
  import { spawnSync } from 'node:child_process';
14
14
 
15
15
  import { exportTarget } from './doctor.mjs';
16
+ import { expandHome, resolvePath } from './paths.mjs';
16
17
 
17
18
  const IGNORED = new Set(['node_modules', '.git', 'docs', 'test', 'tests', 'coverage', 'fixtures']);
18
19
 
19
20
  export function resolveEntry(dir, manifest) {
21
+ const root = resolvePath(dir);
20
22
  const declared = manifest?.dsh?.client?.entry;
21
23
  const exported = manifest?.exports;
22
24
  const subpath = typeof exported === 'string' ? undefined : exportTarget(exported?.['./client']);
23
25
  const candidates = [declared, subpath, 'client.js', 'lib/client.js', 'dist/client.js'].filter((value) => typeof value === 'string');
24
26
  for (const candidate of candidates) {
25
- const absolute = path.resolve(dir, candidate);
27
+ const absolute = path.resolve(root, candidate);
26
28
  if (fs.existsSync(absolute)) return absolute;
27
29
  }
28
30
  return null;
@@ -30,8 +32,8 @@ export function resolveEntry(dir, manifest) {
30
32
 
31
33
  /** Where the installed copy lives, so the host's watcher sees the change. */
32
34
  export function resolveDest(name, { dest, home = path.join(os.homedir(), '.dsh') } = {}) {
33
- if (typeof dest === 'string' && dest.length > 0) return path.resolve(dest);
34
- const profiles = path.join(home, 'profiles');
35
+ if (typeof dest === 'string' && dest.length > 0) return resolvePath(dest);
36
+ const profiles = path.join(resolvePath(home), 'profiles');
35
37
  if (fs.existsSync(profiles) === false) return null;
36
38
  for (const profile of fs.readdirSync(profiles)) {
37
39
  const candidate = path.join(profiles, profile, 'node_modules', name);
@@ -167,8 +169,9 @@ export async function readGraph({ host, timeoutMs = 3000, fetchImpl = fetch }) {
167
169
  }
168
170
 
169
171
  export function watchPlugin({ dir, onChange, debounceMs = 200, io = console }) {
172
+ const root = resolvePath(dir);
170
173
  const timers = new Map();
171
- const watcher = fs.watch(dir, { recursive: true }, (event, file) => {
174
+ const watcher = fs.watch(root, { recursive: true }, (event, file) => {
172
175
  if (typeof file !== 'string') return;
173
176
  const parts = file.split(path.sep);
174
177
  if (parts.some((part) => IGNORED.has(part)) === true) return;
@@ -179,7 +182,7 @@ export function watchPlugin({ dir, onChange, debounceMs = 200, io = console }) {
179
182
  onChange(file);
180
183
  }, debounceMs));
181
184
  });
182
- io.log(`watching ${dir}`);
185
+ io.log(`watching ${root}`);
183
186
  return () => {
184
187
  for (const timer of timers.values()) clearTimeout(timer);
185
188
  watcher.close();
@@ -201,13 +204,14 @@ export async function dev(options) {
201
204
  sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
202
205
  } = options;
203
206
 
204
- const manifestPath = path.join(dir, 'package.json');
207
+ const root = resolvePath(dir);
208
+ const manifestPath = path.join(root, 'package.json');
205
209
  if (fs.existsSync(manifestPath) === false) {
206
- io.error(`dsh-plugin dev: ${dir} has no package.json`);
210
+ io.error(`dsh-plugin dev: ${root} has no package.json`);
207
211
  return 1;
208
212
  }
209
213
  const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
210
- const source = entryOption === undefined ? resolveEntry(dir, manifest) : path.resolve(dir, entryOption);
214
+ const source = entryOption === undefined ? resolveEntry(root, manifest) : path.resolve(root, expandHome(entryOption));
211
215
  if (source === null) {
212
216
  io.error('dsh-plugin dev: no client entry found (dsh.client.entry, client.js, lib/client.js)');
213
217
  return 1;
@@ -217,13 +221,13 @@ export async function dev(options) {
217
221
  io.error(`dsh-plugin dev: ${manifest.name} is not installed in any profile; pass --dest`);
218
222
  return 1;
219
223
  }
220
- const relative = path.relative(dir, source);
224
+ const relative = path.relative(root, source);
221
225
  const target = path.join(destDir, relative);
222
226
  io.log(`${manifest.name}: ${source} -> ${target}`);
223
227
 
224
228
  const sync = async (reason) => {
225
229
  if (buildCommand !== undefined) {
226
- const built = build({ command: buildCommand, cwd: dir, io });
230
+ const built = build({ command: buildCommand, cwd: root, io });
227
231
  if (built.ok === false) {
228
232
  io.error(`build failed (exit ${built.status}); nothing copied`);
229
233
  return { ok: false };
@@ -269,7 +273,7 @@ export async function dev(options) {
269
273
  stopping = true;
270
274
  };
271
275
  process.once('SIGINT', stop);
272
- const close = watchPlugin({ dir, debounceMs, io, onChange: (file) => { void sync(file); } });
276
+ const close = watchPlugin({ dir: root, debounceMs, io, onChange: (file) => { void sync(file); } });
273
277
  await sync('initial');
274
278
  while (stopping === false) await sleep(200);
275
279
  close();
package/lib/doctor.mjs CHANGED
@@ -10,11 +10,37 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
 
12
12
  import { hostCompatibility, parsePartialVersion, parseRange } from './compat.mjs';
13
+ import { resolvePath } from './paths.mjs';
13
14
 
14
15
  export { hostCompatibility } from './compat.mjs';
15
16
 
16
17
  const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
17
18
 
19
+ /**
20
+ * npm publishes and installs by `name`; a missing, empty or malformed one fails
21
+ * at the publish/pack boundary, after every other check has already passed.
22
+ *
23
+ * The shape is npm's "valid for a new package" rule without a dependency:
24
+ * lower-case URL-safe segments, no leading dot/hyphen/underscore, at most 214
25
+ * characters, and not one of the two names npm reserves. `init` uses the same
26
+ * predicate, so a scaffold's name and the preflight that blesses it cannot
27
+ * drift apart.
28
+ */
29
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;
30
+ const MAX_NAME_LENGTH = 214;
31
+ const RESERVED_NAMES = new Set(['node_modules', 'favicon.ico']);
32
+
33
+ export function isValidPackageName(name) {
34
+ return (
35
+ typeof name === 'string' &&
36
+ name.length > 0 &&
37
+ name.length <= MAX_NAME_LENGTH &&
38
+ name === name.trim() &&
39
+ NPM_NAME.test(name) &&
40
+ RESERVED_NAMES.has(name.toLowerCase()) === false
41
+ );
42
+ }
43
+
18
44
  /**
19
45
  * A complete bare version is a comparator set, but it is not a range the market
20
46
  * index can repeat: it pins one version. The parser accepts it, so reject that
@@ -30,9 +56,12 @@ function isRangeExpression(value) {
30
56
  }
31
57
 
32
58
  export function readManifest(dir) {
33
- const manifestPath = path.join(dir, 'package.json');
59
+ // `doctor '~/my-panel'` arrives with a literal tilde from cmd/PowerShell.
60
+ // Resolve it here too, because this is also a public entry point.
61
+ const target = resolvePath(dir);
62
+ const manifestPath = path.join(target, 'package.json');
34
63
  if (fs.existsSync(manifestPath) === false) {
35
- throw new Error(`no package.json in ${dir}`);
64
+ throw new Error(`no package.json in ${target}`);
36
65
  }
37
66
  // Notepad and some VS Code configurations save UTF-8 with a BOM. JSON.parse
38
67
  // rejects it with a bare `Unexpected token`, so strip it and name the file
@@ -59,6 +88,29 @@ export function hostRange(manifest) {
59
88
  return typeof dsh === 'string' && dsh.trim() !== '' ? dsh.trim() : null;
60
89
  }
61
90
 
91
+ /**
92
+ * `doctor` reads this before anything that needs a package name: `verify` packs
93
+ * and installs the tarball under it, and the loader imports the bare name. An
94
+ * empty string and a deleted field both mean "npm cannot publish this", so they
95
+ * get the same actionable answer rather than being treated as present.
96
+ */
97
+ export function checkName(manifest) {
98
+ const name = manifest?.name;
99
+ if (name === undefined || name === null) {
100
+ return 'package.json has no "name", so npm cannot publish or install the package';
101
+ }
102
+ if (typeof name !== 'string') {
103
+ return 'package.json "name" is not a string, so npm cannot publish or install the package';
104
+ }
105
+ if (name.trim() === '') {
106
+ return 'package.json has an empty "name", so npm cannot publish or install the package';
107
+ }
108
+ if (isValidPackageName(name) === false) {
109
+ return `package.json "name" ${JSON.stringify(name)} is not a valid npm package name; use lower-case letters, digits, dots, hyphens or underscores, for example my-plugin or @me/my-plugin`;
110
+ }
111
+ return null;
112
+ }
113
+
62
114
  export function checkVersion(manifest) {
63
115
  const value = version(manifest);
64
116
  if (value === null) return 'package.json has no version';
@@ -98,14 +150,18 @@ export function checkHostCompatibility(manifest, hostVersion) {
98
150
  return hostCompatibility(range, hostVersion);
99
151
  }
100
152
 
101
- export function checkReadme(dir) {
102
- const readmePath = path.join(dir, 'README.md');
103
- if (fs.existsSync(readmePath) === false) return 'README.md is missing';
104
- const text = fs.readFileSync(readmePath, 'utf8');
153
+ /**
154
+ * The README questions that do not depend on where the text came from: is there
155
+ * a Requirements section, and does it name the range the manifest declares.
156
+ *
157
+ * Factored out because `doctor --remote` reads the same README over the GitHub
158
+ * API; a second copy would drift and the two commands would disagree about the
159
+ * same repository.
160
+ */
161
+ export function checkReadmeText(text, manifest) {
105
162
  if (/^#{1,3}\s*Requirements/im.test(text) === false) {
106
163
  return 'README.md has no Requirements section, so users cannot tell which host it needs';
107
164
  }
108
- const { manifest } = readManifest(dir);
109
165
  const range = hostRange(manifest);
110
166
  // ">= 0.2.0" and ">=0.2.0" are the same range; authors write both.
111
167
  const squeeze = (value) => value.replace(/\s+/g, '');
@@ -115,6 +171,12 @@ export function checkReadme(dir) {
115
171
  return null;
116
172
  }
117
173
 
174
+ export function checkReadme(dir) {
175
+ const readmePath = path.join(dir, 'README.md');
176
+ if (fs.existsSync(readmePath) === false) return 'README.md is missing';
177
+ return checkReadmeText(fs.readFileSync(readmePath, 'utf8'), readManifest(dir).manifest);
178
+ }
179
+
118
180
  export function checkPatchFile(dir, manifest) {
119
181
  const bundle = manifest.dsh?.bundle;
120
182
  if (bundle === undefined || typeof bundle.patch !== 'string') return null;
@@ -445,19 +507,21 @@ export function exportsApply(source) {
445
507
 
446
508
  /** Runs every check and returns `{ failures, notes }`. */
447
509
  export function doctor(dir, { installed = false } = {}) {
448
- const { manifest } = readManifest(dir);
510
+ const target = resolvePath(dir);
511
+ const { manifest } = readManifest(target);
449
512
  const checks = [
513
+ ['name', checkName(manifest)],
450
514
  ['version', checkVersion(manifest)],
451
515
  ['engines.dsh', checkHostRange(manifest)],
452
- ['readme', checkReadme(dir)],
516
+ ['readme', checkReadme(target)],
453
517
  ['dsh field', checkDshField(manifest)],
454
- ['patch file', checkPatchFile(dir, manifest)],
455
- ['client entry', checkClientEntry(dir, manifest)],
456
- ['client declaration', checkClientDeclaration(dir, manifest)],
518
+ ['patch file', checkPatchFile(target, manifest)],
519
+ ['client entry', checkClientEntry(target, manifest)],
520
+ ['client declaration', checkClientDeclaration(target, manifest)],
457
521
  // After install the tarball is already unpacked, so `files` cannot be used to
458
522
  // decide what shipped: npm always ships package.json and the README.
459
523
  ['files list', installed === true ? null : checkFilesList(manifest)],
460
- ['root export', checkRootExport(dir, manifest)],
524
+ ['root export', checkRootExport(target, manifest)],
461
525
  ];
462
526
  const failures = checks.filter(([, result]) => result !== null && typeof result === 'string');
463
527
  return {
package/lib/fix.mjs CHANGED
@@ -17,6 +17,7 @@ import path from 'node:path';
17
17
 
18
18
  import { hostRangePlan, satisfiesRange } from './compat.mjs';
19
19
  import { checkHostRange, doctor, hostRange } from './doctor.mjs';
20
+ import { resolvePath } from './paths.mjs';
20
21
 
21
22
  /** The oldest host the toolkit itself supports, and the range `init` writes. */
22
23
  export const DEFAULT_ENGINES = '>=0.2.0';
@@ -82,6 +83,52 @@ function failure(check, message) {
82
83
  return { ok: false, failures: [{ check, message }] };
83
84
  }
84
85
 
86
+ /**
87
+ * Decide what the `engines.dsh` edit should be for one manifest.
88
+ *
89
+ * The local fixer and the remote planner share this decision so the range a
90
+ * `fix --remote` plan prints is exactly the range `--write` applies in a
91
+ * checkout. `manifest` is the object after the edit when there is one;
92
+ * `noop` means the current range already clears `doctor` and `force` does not
93
+ * ask for a replacement.
94
+ */
95
+ export function planEnginesEdit(manifest, { range, host, force = false } = {}) {
96
+ const requested = resolveEnginesRange({ range, host });
97
+ if (requested.error !== undefined) {
98
+ return failure('host', requested.error);
99
+ }
100
+ const { proposed } = requested;
101
+ if (isHostRange(proposed) === false) {
102
+ return failure('engines.dsh', `"${proposed}" is not a semver range, so it would not clear the doctor check`);
103
+ }
104
+
105
+ const current = hostRange(manifest);
106
+ const correct = current !== null && checkHostRange(manifest) === null;
107
+ const same = normalize(current) === normalize(proposed);
108
+ const forced = force === true || requested.force === true;
109
+ const noop = correct === true && (forced !== true || same === true);
110
+ const engines =
111
+ manifest.engines !== null && typeof manifest.engines === 'object' && Array.isArray(manifest.engines) === false
112
+ ? manifest.engines
113
+ : {};
114
+ const next = noop === true ? null : { ...manifest, engines: { ...engines, dsh: proposed } };
115
+
116
+ return {
117
+ ok: true,
118
+ proposed,
119
+ current,
120
+ correct,
121
+ same,
122
+ forced,
123
+ noop,
124
+ manifest: next,
125
+ reason: noop === true ? 'already-correct' : current === null ? 'missing' : correct === true ? 'different' : 'not-a-range',
126
+ host: requested.host,
127
+ nextMajor: requested.nextMajor,
128
+ why: requested.why,
129
+ };
130
+ }
131
+
85
132
  /** Keep the indentation and the final newline the manifest already had. */
86
133
  function formatting(raw) {
87
134
  const indent = /^[\t ]+"/m.exec(raw);
@@ -210,7 +257,7 @@ export function unifiedDiff(before, after, { file = 'package.json', context = 3
210
257
  * result.
211
258
  */
212
259
  export function fixEngines({ dir = '.', range, host, write = false, force = false } = {}) {
213
- const target = path.resolve(dir);
260
+ const target = resolvePath(dir);
214
261
  const manifestPath = path.join(target, 'package.json');
215
262
  if (fs.existsSync(manifestPath) === false) {
216
263
  return failure('manifest', `no package.json in ${target}`);
@@ -228,20 +275,11 @@ export function fixEngines({ dir = '.', range, host, write = false, force = fals
228
275
  return failure('manifest', `${manifestPath} does not hold a JSON object`);
229
276
  }
230
277
 
231
- const requested = resolveEnginesRange({ range, host });
232
- if (requested.error !== undefined) {
233
- return failure('host', requested.error);
234
- }
235
- const { proposed } = requested;
236
- if (isHostRange(proposed) === false) {
237
- return failure('engines.dsh', `"${proposed}" is not a semver range, so it would not clear the doctor check`);
238
- }
278
+ const planned = planEnginesEdit(manifest, { range, host, force });
279
+ if (planned.ok !== true) return planned;
239
280
 
240
- const current = hostRange(manifest);
241
- const correct = current !== null && checkHostRange(manifest) === null;
242
- const same = normalize(current) === normalize(proposed);
243
- const forced = force === true || requested.force === true;
244
- if (correct === true && (forced !== true || same === true)) {
281
+ const { proposed, current } = planned;
282
+ if (planned.noop === true) {
245
283
  return {
246
284
  ok: true,
247
285
  dir: target,
@@ -252,18 +290,13 @@ export function fixEngines({ dir = '.', range, host, write = false, force = fals
252
290
  changed: false,
253
291
  written: false,
254
292
  reason: 'already-correct',
255
- host: requested.host,
256
- nextMajor: requested.nextMajor,
257
- why: requested.why,
293
+ host: planned.host,
294
+ nextMajor: planned.nextMajor,
295
+ why: planned.why,
258
296
  };
259
297
  }
260
298
 
261
- const engines =
262
- manifest.engines !== null && typeof manifest.engines === 'object' && Array.isArray(manifest.engines) === false
263
- ? manifest.engines
264
- : {};
265
- const next = { ...manifest, engines: { ...engines, dsh: proposed } };
266
- const content = renderManifest(next, raw);
299
+ const content = renderManifest(planned.manifest, raw);
267
300
 
268
301
  let written = false;
269
302
  if (write === true) {
@@ -280,10 +313,10 @@ export function fixEngines({ dir = '.', range, host, write = false, force = fals
280
313
  range: proposed,
281
314
  changed: true,
282
315
  written,
283
- reason: current === null ? 'missing' : correct === true ? 'different' : 'not-a-range',
284
- host: requested.host,
285
- nextMajor: requested.nextMajor,
286
- why: requested.why,
316
+ reason: planned.reason,
317
+ host: planned.host,
318
+ nextMajor: planned.nextMajor,
319
+ why: planned.why,
287
320
  };
288
321
  }
289
322
 
@@ -292,6 +325,11 @@ function manualRepair(failure, dir, manifest) {
292
325
  const packageFile = path.join(dir, 'package.json');
293
326
  const at = (file) => ({ file, path: path.relative(dir, file) || path.basename(file) });
294
327
  switch (failure.check) {
328
+ case 'name':
329
+ return {
330
+ ...at(packageFile),
331
+ manual: 'set "name" to the npm package name, for example my-plugin or @me/my-plugin',
332
+ };
295
333
  case 'version':
296
334
  return {
297
335
  ...at(packageFile),
@@ -369,7 +407,7 @@ function setField(target, field, value) {
369
407
  * be worse than saying so. A plan is pure: it never writes.
370
408
  */
371
409
  export function repairPlan({ dir = '.', range, host } = {}) {
372
- const target = path.resolve(dir);
410
+ const target = resolvePath(dir);
373
411
  const manifestPath = path.join(target, 'package.json');
374
412
  const requested = resolveEnginesRange({ range, host });
375
413
  if (requested.error !== undefined) {
package/lib/github.mjs CHANGED
@@ -10,6 +10,7 @@ import fs from 'node:fs';
10
10
  import os from 'node:os';
11
11
  import path from 'node:path';
12
12
  import { run } from './exec.mjs';
13
+ import { expandHome } from './paths.mjs';
13
14
 
14
15
  const UA = 'dsh-plugin-toolkit';
15
16
 
@@ -21,9 +22,9 @@ const UA = 'dsh-plugin-toolkit';
21
22
  export function parseTarget(input) {
22
23
  const raw = typeof input === 'string' ? input.trim() : '';
23
24
  if (raw === '') return { kind: 'empty' };
24
- // `~/kit` is how a person writes a home folder; `fs.existsSync` would call it
25
- // a search and send the name to github.com.
26
- const expanded = raw === '~' || raw.startsWith('~/') === true ? path.join(os.homedir(), raw.slice(1)) : raw;
25
+ // `~/kit` (and the Windows `~\kit`) is how a person writes a home folder;
26
+ // `fs.existsSync` would call it a search and send the name to github.com.
27
+ const expanded = expandHome(raw);
27
28
  if (fs.existsSync(expanded) === true) return { kind: 'local', dir: path.resolve(expanded) };
28
29
 
29
30
  const url = raw.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s#?]+)(?:\/.*)?$/i);
@@ -7,9 +7,10 @@
7
7
  import fs from 'node:fs';
8
8
 
9
9
  import { checkHostRange } from './doctor.mjs';
10
+ import { resolvePath } from './paths.mjs';
10
11
 
11
12
  export function readIndex(file) {
12
- return JSON.parse(fs.readFileSync(file, 'utf8'));
13
+ return JSON.parse(fs.readFileSync(resolvePath(file), 'utf8'));
13
14
  }
14
15
 
15
16
  export function findPlugin(index, name) {
@@ -81,5 +82,5 @@ export function auditVersions(index, name) {
81
82
  }
82
83
 
83
84
  export function writeIndex(file, index) {
84
- fs.writeFileSync(file, `${JSON.stringify(index, null, 2)}\n`);
85
+ fs.writeFileSync(resolvePath(file), `${JSON.stringify(index, null, 2)}\n`);
85
86
  }
package/lib/init.mjs CHANGED
@@ -8,16 +8,18 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
 
11
+ import { isValidPackageName } from './doctor.mjs';
12
+ import { resolvePath } from './paths.mjs';
13
+
11
14
  // The scaffold pins the toolkit it was generated by, not a number typed once:
12
15
  // a scaffold that installs two minor versions behind is the first thing a new
13
16
  // author sees and the last thing anyone updates.
14
17
  const VERSION = JSON.parse(
15
18
  fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'),
16
19
  ).version;
17
- const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
18
20
 
19
21
  export function checkName(name) {
20
- if (typeof name !== 'string' || NPM_NAME.test(name) === false) {
22
+ if (isValidPackageName(name) === false) {
21
23
  return 'name must be a valid npm package name, e.g. my-plugin or @me/my-plugin';
22
24
  }
23
25
  return null;
@@ -192,7 +194,10 @@ export function init({ dir, name, title, force = false }) {
192
194
  const problem = checkName(name);
193
195
  if (problem !== null) return { ok: false, failures: [{ check: 'name', message: problem }] };
194
196
 
195
- const target = path.resolve(dir);
197
+ // `init '~/my-panel'` reaches this function with the tilde intact on
198
+ // cmd/PowerShell. Expand it here as well as in the CLI so a direct caller
199
+ // cannot create a directory literally named `~` either.
200
+ const target = resolvePath(dir);
196
201
  if (fs.existsSync(target) === true) {
197
202
  const entries = fs.readdirSync(target).filter((entry) => entry !== '.git');
198
203
  if (entries.length > 0 && force !== true) {
package/lib/paths.mjs ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * User-supplied paths, before they reach the filesystem.
3
+ *
4
+ * A POSIX shell expands `~/my-panel` before the program starts. `cmd` and
5
+ * PowerShell do not: they hand the literal string to the program, so
6
+ * `path.resolve('~/my-panel')` quietly creates a directory literally named `~`
7
+ * in the current working directory. Every command that accepts a folder or a
8
+ * file from a person has to expand the tilde itself, or the documented example
9
+ * writes somewhere surprising on Windows.
10
+ */
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+
14
+ /**
15
+ * Expand a leading `~` the way a POSIX shell would.
16
+ *
17
+ * `~\x` is the Windows spelling of a child path, so both separators are
18
+ * treated as separators here; `path.join` then uses the host one. `~someone`
19
+ * is a different user, not this home directory, and is left alone.
20
+ */
21
+ export function expandHome(value, home = os.homedir()) {
22
+ const text = String(value ?? '').trim();
23
+ if (text === '' || /^~($|[\\/])/u.test(text) === false) {
24
+ return text;
25
+ }
26
+ const rest = text.slice(1).replace(/^[\\/]+/u, '').split(/[\\/]+/u).join('/');
27
+ return path.join(home, rest);
28
+ }
29
+
30
+ /**
31
+ * Expand a leading `~` and make the result absolute against the current
32
+ * working directory. This is the one step every filesystem-facing command
33
+ * applies to a user-named path, so `init`, `doctor`, `fix`, `verify`, `dev`,
34
+ * `release` and the audit flags all resolve the same way.
35
+ */
36
+ export function resolvePath(value, { home = os.homedir(), cwd = process.cwd() } = {}) {
37
+ return path.resolve(cwd, expandHome(value, home));
38
+ }
package/lib/release.mjs CHANGED
@@ -10,6 +10,7 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
 
12
12
  import { doctor } from './doctor.mjs';
13
+ import { expandHome, resolvePath } from './paths.mjs';
13
14
  import { addVersion, buildEntry, readIndex, writeIndex } from './index-file.mjs';
14
15
  import { publishedAt, waitForVersion } from './registry.mjs';
15
16
  import { defaultGh, mergePr, openIndexPr, waitForChecks } from './pr.mjs';
@@ -94,7 +95,7 @@ export function dirtyPaths(dir, limit = 3, run) {
94
95
  * and the exact commands.
95
96
  */
96
97
  export function plan({ dir = process.cwd(), version, name, tagPrefix = 'plugin-v', indexFile = 'market/index.json', marketDir }) {
97
- const report = doctor(dir);
98
+ const report = doctor(resolvePath(dir));
98
99
  const resolvedName = name ?? report.manifest.name ?? 'this-plugin';
99
100
  const resolvedVersion = version ?? report.manifest.version ?? '0.0.0';
100
101
  const tag = tagName(resolvedVersion, tagPrefix);
@@ -130,11 +131,13 @@ export async function release(options) {
130
131
  onChange,
131
132
  } = options;
132
133
 
133
- const gitRun = options.git ?? ((args) => git(dir, args));
134
+ const root = resolvePath(dir);
135
+ const indexPathFile = expandHome(indexFile);
136
+ const gitRun = options.git ?? ((args) => git(root, args));
134
137
 
135
138
  let report;
136
139
  try {
137
- report = doctor(dir);
140
+ report = doctor(root);
138
141
  } catch (error) {
139
142
  // A folder without package.json is a preflight failure, not a crash: the
140
143
  // command's job is to say what is wrong, and a stack trace is not an answer.
@@ -148,13 +151,13 @@ export async function release(options) {
148
151
  const version = report.manifest.version;
149
152
  const tag = tagName(version, tagPrefix);
150
153
 
151
- const resuming = tagExists(dir, tag, gitRun) === true;
152
- if (resuming === true && tagPointsAtHead(dir, tag, gitRun) === false) {
154
+ const resuming = tagExists(root, tag, gitRun) === true;
155
+ if (resuming === true && tagPointsAtHead(root, tag, gitRun) === false) {
153
156
  // A tag at another commit is not a resume: moving it would rewrite what the
154
157
  // earlier release published. Name where it points, where HEAD is, and the
155
158
  // exact commands that remove it so the next attempt can tag this commit.
156
- const target = tagCommit(dir, tag, gitRun);
157
- const head = headCommit(dir, gitRun);
159
+ const target = tagCommit(root, tag, gitRun);
160
+ const head = headCommit(root, gitRun);
158
161
  const targetText = target ?? 'an unknown commit';
159
162
  const headText = head ?? 'an unknown commit';
160
163
  return {
@@ -170,8 +173,8 @@ export async function release(options) {
170
173
  // A resume does not create a tag, so the clean-tree rule that protects the
171
174
  // tag does not apply: the index write from a previous attempt is allowed to
172
175
  // be the only uncommitted change.
173
- if (workingTreeIsClean(dir, gitRun) === false) {
174
- const dirty = dirtyPaths(dir, 3, gitRun);
176
+ if (workingTreeIsClean(root, gitRun) === false) {
177
+ const dirty = dirtyPaths(root, 3, gitRun);
175
178
  const listed = dirty.length > 0 ? ` (${dirty.join(', ')})` : '';
176
179
  return {
177
180
  ok: false,
@@ -188,7 +191,7 @@ export async function release(options) {
188
191
  // the same command covers both kinds of repository.
189
192
  if (options.publish === true) {
190
193
  try {
191
- (options.publishPackage ?? publishPackage)(dir);
194
+ (options.publishPackage ?? publishPackage)(root);
192
195
  } catch (error) {
193
196
  const detail = String(error.stderr ?? error.message).trim().split('\n').slice(-1)[0];
194
197
  return { ok: false, stage: 'publish', failures: [{ check: 'publish', message: `npm publish failed: ${detail}` }] };
@@ -234,11 +237,20 @@ export async function release(options) {
234
237
  }
235
238
 
236
239
  const timestamp = publishedAt(waited.document, version);
237
- const entry = buildEntry({ version, publishTimestamp: timestamp, hostRange: report.notes.hostRange });
240
+ // Building the entry can fail before the index is even read (a malformed
241
+ // `engines.dsh` is normally caught by doctor, but a caller that reaches this
242
+ // point must still get a result, not an exception). Keep the failure in the
243
+ // same `index` stage as an `addVersion` rejection and never write anything.
244
+ let entry;
245
+ try {
246
+ entry = buildEntry({ version, publishTimestamp: timestamp, hostRange: report.notes.hostRange });
247
+ } catch (error) {
248
+ return { ok: false, stage: 'index', failures: [{ check: 'index', message: error.message }] };
249
+ }
238
250
  // Most plugins are listed in someone else's index: `--market` points at a
239
251
  // checkout of that repository, and the entry plus the pull request land there.
240
- const indexRoot = typeof marketDir === 'string' && marketDir.length > 0 ? path.resolve(marketDir) : dir;
241
- const indexPath = path.join(indexRoot, indexFile);
252
+ const indexRoot = typeof marketDir === 'string' && marketDir.length > 0 ? resolvePath(marketDir) : root;
253
+ const indexPath = path.join(indexRoot, indexPathFile);
242
254
  let indexUpdate = null;
243
255
  if (fs.existsSync(indexPath) === true) {
244
256
  try {
@@ -272,11 +284,11 @@ export async function release(options) {
272
284
  // a green CI and a merge; doing that by hand is where "forgot to open the PR"
273
285
  // happens.
274
286
  const ghRunner = options.gh ?? defaultGh(indexRoot);
275
- const marketGit = options.marketGit ?? (indexRoot === dir ? options.git : ((args) => git(indexRoot, args)));
287
+ const marketGit = options.marketGit ?? (indexRoot === root ? options.git : ((args) => git(indexRoot, args)));
276
288
  const pull = await openIndexPr({
277
289
  dir: indexRoot,
278
290
  git: marketGit,
279
- indexFile,
291
+ indexFile: indexPathFile,
280
292
  version,
281
293
  base: options.base ?? 'main',
282
294
  branch: options.branch,