@nx-devkit/prepare-for-release 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,42 +14,27 @@ Requires `@nx/devkit` `^22 || ^23` (peer).
14
14
 
15
15
  ## Bootstrap
16
16
 
17
- Run the `init` generator — it registers the plugin in `nx.json` and creates a `tools` project with the `prepare-for-release` target:
17
+ Register the plugin in `nx.json`:
18
18
 
19
- ```bash
20
- npx nx g @nx-devkit/prepare-for-release:init
19
+ ```jsonc
20
+ { "plugins": ["@nx-devkit/prepare-for-release"] }
21
21
  ```
22
22
 
23
- <!-- sym:generators.json → generators.init.factory,schema -->
24
-
25
- Or do it manually:
23
+ That's all — `createNodesV2` infers a `prepare-for-release` target on every non-root `package.json` that has a `name` and is not `private: true`. Then:
26
24
 
27
- 1. Register the plugin in `nx.json` so `createNodesV2` can detect release-bootstrap projects:
28
-
29
- ```jsonc
30
- { "plugins": ["@nx-devkit/prepare-for-release"] }
25
+ ```bash
26
+ npx nx run-many -t prepare-for-release
31
27
  ```
32
28
 
33
- 2. Create `tools/project.json` wired to the executor:
29
+ Each target processes exactly one package; already-published packages skip via `npm view`. Opt a package out with `"private": true`, or exclude project-root prefixes via plugin options:
34
30
 
35
31
  ```jsonc
36
- {
37
- "name": "tools",
38
- "targets": {
39
- "prepare-for-release": {
40
- "executor": "@nx-devkit/prepare-for-release:publish-placeholder"
41
- }
42
- }
43
- }
32
+ { "plugins": [{ "plugin": "@nx-devkit/prepare-for-release", "options": { "exclude": ["fixtures"] } }] }
44
33
  ```
45
34
 
46
- The plugin's `createNodesV2` scans `**/project.json` for projects whose targets reference its executor and surfaces them on the graph.
47
-
48
- Then run:
35
+ <!-- sym:generators.json → generators.init.factory,schema -->
49
36
 
50
- ```bash
51
- npx nx run tools:prepare-for-release
52
- ```
37
+ Alternatively, `npx nx g @nx-devkit/prepare-for-release:init` registers the plugin and creates a legacy `tools` project whose single `prepare-for-release` target scans `packages/*`. When per-package targets are inferred, the tools target is suppressed so `nx run-many -t` never processes a package twice — set `packageTargets: false` in plugin options to keep tools-only mode.
53
38
 
54
39
  ## What the executor does
55
40
 
@@ -62,6 +47,10 @@ For each package under `packages/*` (or your `scope` filter):
62
47
 
63
48
  Already-published packages are skipped on every run. Packages marked `private: true` are ignored entirely — no `npm view`, no publish.
64
49
 
50
+ ### Interactive auth (EOTP)
51
+
52
+ When npm demands a one-time password, the executor doesn't leave you guessing: it detects the `EOTP` failure, recovers the real approval URL (npm masks it in non-TTY output), prints it, polls for your approval, and retries with `--otp`. Requires an `npm login` session token in `.npmrc`.
53
+
65
54
  ## Options
66
55
 
67
56
  <!-- option reference consistent with src/executors/publish-placeholder/schema.json -->
@@ -69,6 +58,7 @@ Already-published packages are skipped on every run. Packages marked `private: t
69
58
  ```jsonc
70
59
  // tools/project.json → targets.prepare-for-release.options
71
60
  {
61
+ "packageJson": "packages/foo/package.json",
72
62
  "scope": ["@nx-devkit"],
73
63
  "placeholderTag": "placeholder",
74
64
  "placeholderVersion": "0.0.0",
@@ -81,6 +71,7 @@ Already-published packages are skipped on every run. Packages marked `private: t
81
71
 
82
72
  | Option | Default | Effect |
83
73
  |---|---|---|
74
+ | `packageJson` | unset | Process only this manifest (workspace-relative or absolute path). Set automatically by the per-package inferred target; leave unset for the `packages/*` scan. |
84
75
  | `scope` | every package in `packages/*` | Package scope prefixes to check. |
85
76
  | `placeholderTag` | `placeholder` | npm dist-tag applied to the placeholder publish. |
86
77
  | `placeholderVersion` | `0.0.0` | Version written into the temporary placeholder manifest. |
@@ -1,5 +1,7 @@
1
1
  //#region src/executors/publish-placeholder/executor.d.ts
2
2
  interface NxPrepareForReleaseOptions {
3
+ /** Path to a single package.json (workspace-relative or absolute). When set, only that package is processed — used by the per-package `prepare-for-release` target. */
4
+ packageJson?: string;
3
5
  /** Package scopes to check. Default: derived from packages/* names in the workspace. */
4
6
  scope?: string[];
5
7
  /** Npm dist-tag applied to the placeholder publish. Default: "placeholder". */
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { dirname, join } from "node:path";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
5
  import { spawn, spawnSync } from "node:child_process";
6
6
  import { glob } from "tinyglobby";
7
7
  //#region src/executors/publish-placeholder/executor.ts
@@ -10,9 +10,14 @@ const DEFAULT_TAG = "placeholder";
10
10
  const DEFAULT_VERSION = "0.0.0";
11
11
  const TRUST_REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
12
12
  const NPM_SUBPROCESS_TIMEOUT_MS = 12e4;
13
+ const EOTP_RE = /\bEOTP\b|one-time password/i;
14
+ const WEB_AUTH_TIMEOUT_MS = 5 * 6e4;
15
+ const WEB_AUTH_POLL_MS = 4e3;
16
+ const WEB_AUTH_FETCH_TIMEOUT_MS = 15e3;
13
17
  function resolveOptions(options) {
14
18
  return {
15
19
  dryRun: options.dryRun ?? false,
20
+ packageJson: options.packageJson,
16
21
  placeholderTag: options.placeholderTag ?? DEFAULT_TAG,
17
22
  placeholderVersion: options.placeholderVersion ?? DEFAULT_VERSION,
18
23
  registry: options.registry ?? DEFAULT_REGISTRY,
@@ -207,14 +212,105 @@ function runTrustFor(pkgName, trustRepo, registry) {
207
212
  });
208
213
  });
209
214
  }
210
- async function publishOnePackage(pkgRoot, name, resolved) {
215
+ /**
216
+ * Locate an npm auth token for `registry`: prefers a host-scoped
217
+ * `//host/:_authToken=` entry in `<cwd>/.npmrc`, then `~/.npmrc`, then an
218
+ * unscoped `_authToken=` line. Host-scoped tokens for OTHER registries
219
+ * are never returned — sending one to the wrong host would leak it.
220
+ */
221
+ function readNpmAuthToken(registry, cwd) {
222
+ const url = new URL(registry);
223
+ const registryKey = `//${url.host}${url.pathname.replace(/\/+$/, "")}`;
224
+ const keyRe = new RegExp(`${registryKey.replace(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)}/:_authToken=(\\S+)`);
225
+ const candidates = [join(cwd, ".npmrc"), join(homedir(), ".npmrc")];
226
+ for (const rcPath of candidates) {
227
+ let text;
228
+ try {
229
+ text = readFileSync(rcPath, "utf8");
230
+ } catch {
231
+ continue;
232
+ }
233
+ const hostMatch = text.match(keyRe);
234
+ const unscopedMatch = text.match(/^\s*_authToken\s*=\s*(\S+)/m);
235
+ const match = hostMatch ?? unscopedMatch;
236
+ if (match) return match[1];
237
+ }
238
+ return null;
239
+ }
240
+ /**
241
+ * npm masks the EOTP auth URL in non-TTY output. Replicating the publish
242
+ * PUT with `npm-auth-type: web` makes the registry return the real
243
+ * authUrl/doneUrl pair in the 401 body.
244
+ */
245
+ async function requestWebAuthUrls(pkgName, registry, token) {
246
+ const base = registry.endsWith("/") ? registry.slice(0, -1) : registry;
247
+ const res = await fetch(`${base}/${pkgName.replace("/", "%2f")}`, {
248
+ body: "{}",
249
+ headers: {
250
+ authorization: `Bearer ${token}`,
251
+ "content-type": "application/json",
252
+ "npm-auth-type": "web",
253
+ "npm-command": "publish"
254
+ },
255
+ method: "PUT",
256
+ signal: AbortSignal.timeout(WEB_AUTH_FETCH_TIMEOUT_MS)
257
+ });
258
+ const text = await res.text();
259
+ let parsed = {};
260
+ try {
261
+ const body = JSON.parse(text);
262
+ if (typeof body === "object" && body !== null) parsed = body;
263
+ } catch {}
264
+ if (!parsed.authUrl || !parsed.doneUrl) throw new Error(`npm web-auth probe for ${pkgName} returned no auth URL (HTTP ${res.status}): ${text}`);
265
+ return {
266
+ authUrl: parsed.authUrl,
267
+ doneUrl: parsed.doneUrl
268
+ };
269
+ }
270
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
271
+ /** Poll the registry done endpoint until the web approval yields an OTP. */
272
+ async function pollForWebAuthOtp(doneUrl, token) {
273
+ const deadline = Date.now() + WEB_AUTH_TIMEOUT_MS;
274
+ while (Date.now() < deadline) {
275
+ const res = await fetch(doneUrl, {
276
+ headers: { authorization: `Bearer ${token}` },
277
+ signal: AbortSignal.timeout(WEB_AUTH_FETCH_TIMEOUT_MS)
278
+ }).catch(() => null);
279
+ if (res?.ok) {
280
+ const body = await res.json().catch(() => null);
281
+ if (body?.otp) return body.otp;
282
+ }
283
+ await sleep(WEB_AUTH_POLL_MS);
284
+ }
285
+ return null;
286
+ }
287
+ function runNpmPublish(npmCmd, tarballPath, resolved, otp) {
288
+ const args = publishArgs(tarballPath, resolved.registry, resolved.placeholderTag);
289
+ if (otp) args.push("--otp", otp);
290
+ const result = spawnWithTimeout(npmCmd, args, { encoding: "utf8" });
291
+ if (result.stdout) process.stdout.write(result.stdout);
292
+ if (result.stderr) process.stderr.write(result.stderr);
293
+ return result;
294
+ }
295
+ async function publishOnePackage(pkgRoot, name, resolved, workspaceRoot) {
211
296
  const { tarballPath, tempDir } = await buildPlaceholderTarball(pkgRoot, name, resolved.placeholderVersion, resolved.registry);
212
297
  try {
213
- const publishResult = spawnWithTimeout(resolveNpmCommand(), publishArgs(tarballPath, resolved.registry, resolved.placeholderTag), {
214
- encoding: "utf8",
215
- stdio: "inherit"
216
- });
217
- if (publishResult.status !== 0) throw new Error(`npm publish failed for ${name} (exit ${publishResult.status})`);
298
+ const npmCmd = resolveNpmCommand();
299
+ let result = runNpmPublish(npmCmd, tarballPath, resolved);
300
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`;
301
+ if (result.status !== 0 && EOTP_RE.test(output)) {
302
+ const token = readNpmAuthToken(resolved.registry, workspaceRoot);
303
+ if (!token) throw new Error(`npm publish requires a one-time password for ${name}, but no npm auth token was found in .npmrc. Run \`npm login\` first.`);
304
+ const { authUrl, doneUrl } = await requestWebAuthUrls(name, resolved.registry, token);
305
+ console.log(`\n npm requires one-time authorization for ${name}.\n Open this URL to approve the publish:\n\n ${authUrl}\n\n Waiting for approval...`);
306
+ const otp = await pollForWebAuthOtp(doneUrl, token);
307
+ if (!otp) throw new Error(`Timed out waiting for npm web authorization for ${name}`);
308
+ result = runNpmPublish(npmCmd, tarballPath, resolved, otp);
309
+ }
310
+ if (result.status !== 0) {
311
+ const stderr = (result.stderr ?? "").toString();
312
+ throw new Error(`npm publish failed for ${name} (exit ${result.status})${stderr ? `: ${stderr}` : ""}`);
313
+ }
218
314
  } finally {
219
315
  await rm(tempDir, {
220
316
  force: true,
@@ -222,7 +318,7 @@ async function publishOnePackage(pkgRoot, name, resolved) {
222
318
  }).catch(() => void 0);
223
319
  }
224
320
  }
225
- async function processPackage(pkgJsonPath, resolved, acc) {
321
+ async function processPackage(pkgJsonPath, resolved, acc, workspaceRoot) {
226
322
  const parsed = readPackageJsonSafe(pkgJsonPath);
227
323
  if (!parsed) return "ignored";
228
324
  const name = typeof parsed.name === "string" ? parsed.name : null;
@@ -237,14 +333,14 @@ async function processPackage(pkgJsonPath, resolved, acc) {
237
333
  acc.trustCommands.push(trustCommandFor(name, resolved.trustRepo, resolved.registry));
238
334
  return "published";
239
335
  }
240
- await publishOnePackage(dirname(pkgJsonPath), name, resolved);
336
+ await publishOnePackage(dirname(pkgJsonPath), name, resolved, workspaceRoot);
241
337
  acc.published.push(name);
242
338
  acc.trustCommands.push(trustCommandFor(name, resolved.trustRepo, resolved.registry));
243
339
  return "published";
244
340
  }
245
341
  async function publishPlaceholderExecutor(options, context) {
246
342
  const resolved = resolveOptions(options);
247
- const pkgDirs = await glob(["packages/*/package.json"], {
343
+ const pkgDirs = resolved.packageJson ? [isAbsolute(resolved.packageJson) ? resolved.packageJson : join(context.root, resolved.packageJson)] : await glob(["packages/*/package.json"], {
248
344
  absolute: true,
249
345
  cwd: context.root,
250
346
  onlyFiles: true
@@ -254,7 +350,7 @@ async function publishPlaceholderExecutor(options, context) {
254
350
  skipped: [],
255
351
  trustCommands: []
256
352
  };
257
- for (const pkgJsonPath of pkgDirs) await processPackage(pkgJsonPath, resolved, acc);
353
+ for (const pkgJsonPath of pkgDirs) await processPackage(pkgJsonPath, resolved, acc, context.root);
258
354
  if (existsSync(join(context.root, "scripts/trust-github.sh"))) {}
259
355
  if (acc.published.length > 0) console.log(`\nPublished: ${acc.published.join(", ")}`);
260
356
  if (acc.skipped.length > 0) console.log(`Skipped: ${acc.skipped.join(", ")}`);
package/dist/plugin.d.mts CHANGED
@@ -6,6 +6,15 @@ interface NxPrepareForReleasePluginOptions {
6
6
  toolsProject?: string;
7
7
  /** Target name inferred on the tools project. */
8
8
  targetName?: string;
9
+ /** Project-root prefixes excluded from per-package inference (e.g. ["fixtures"]). */
10
+ exclude?: string[];
11
+ /**
12
+ * Infer `prepare-for-release` on every publishable package.json.
13
+ * Default: true. Set false to keep only the legacy tools-project mode —
14
+ * when per-package targets exist, the tools target is suppressed so
15
+ * `nx run-many -t` never processes a package twice.
16
+ */
17
+ packageTargets?: boolean;
9
18
  }
10
19
  /**
11
20
  * Detect whether a directory is a release-bootstrap site: it contains a
@@ -14,10 +23,15 @@ interface NxPrepareForReleasePluginOptions {
14
23
  * `tools` project created by the init generator.
15
24
  */
16
25
  declare function isReleaseBootstrapProject(configFile: string, workspaceRoot: string, executor?: string): boolean;
26
+ /**
27
+ * Read a package.json and return its name when it is publishable
28
+ * (has a `name` and is not `private: true`), otherwise null.
29
+ */
30
+ declare function publishablePackageName(configFile: string, workspaceRoot: string): string | null;
17
31
  declare const createNodesV2: CreateNodesV2<NxPrepareForReleasePluginOptions>;
18
32
  declare const plugin: {
19
33
  createNodesV2: CreateNodesV2<NxPrepareForReleasePluginOptions>;
20
34
  name: string;
21
35
  };
22
36
  //#endregion
23
- export { NxPrepareForReleasePluginOptions, createNodesV2, plugin as default, isReleaseBootstrapProject };
37
+ export { NxPrepareForReleasePluginOptions, createNodesV2, plugin as default, isReleaseBootstrapProject, publishablePackageName };
package/dist/plugin.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { dirname, isAbsolute, join } from "node:path";
2
+ import { basename, dirname, isAbsolute, join } from "node:path";
3
3
  //#region src/plugin.ts
4
4
  const PLUGIN_NAME = "@nx-devkit/prepare-for-release";
5
5
  /**
@@ -27,26 +27,62 @@ function isReleaseBootstrapProject(configFile, workspaceRoot, executor = `${PLUG
27
27
  throw error;
28
28
  }
29
29
  }
30
- const createNodesV2 = ["**/project.json", (configFiles, options = {}, context) => {
30
+ /**
31
+ * Read a package.json and return its name when it is publishable
32
+ * (has a `name` and is not `private: true`), otherwise null.
33
+ */
34
+ function publishablePackageName(configFile, workspaceRoot) {
35
+ const absPath = isAbsolute(configFile) ? configFile : join(workspaceRoot, configFile);
36
+ let contents;
37
+ try {
38
+ contents = readFileSync(absPath, "utf8");
39
+ } catch (error) {
40
+ if (error.code === "ENOENT") return null;
41
+ throw error;
42
+ }
43
+ try {
44
+ const raw = JSON.parse(contents);
45
+ if (typeof raw.name !== "string" || raw.private === true) return null;
46
+ return raw.name;
47
+ } catch (error) {
48
+ if (error instanceof SyntaxError) return null;
49
+ throw error;
50
+ }
51
+ }
52
+ const createNodesV2 = ["**/{package,project}.json", (configFiles, options = {}, context) => {
31
53
  const targetName = options.targetName ?? "prepare-for-release";
32
54
  const toolsProjectRoot = options.toolsProject?.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
33
- const results = [];
55
+ const exclude = (options.exclude ?? []).map((e) => e.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, ""));
56
+ const packageResults = [];
57
+ const toolsResults = [];
58
+ let publishableManifests = 0;
34
59
  for (const configFile of configFiles) {
35
60
  const normalized = configFile.replace(/\\/g, "/");
36
- if (!isReleaseBootstrapProject(normalized, context.workspaceRoot)) continue;
37
61
  const projectRoot = dirname(normalized).replace(/\/+$/, "");
38
62
  if (projectRoot === "" || projectRoot === "." || projectRoot === context.workspaceRoot) continue;
39
- if (toolsProjectRoot && projectRoot !== toolsProjectRoot) continue;
40
- results.push([configFile, { projects: { [projectRoot]: { targets: { [targetName]: {
63
+ if (basename(normalized) === "project.json") {
64
+ if (!isReleaseBootstrapProject(normalized, context.workspaceRoot)) continue;
65
+ if (toolsProjectRoot && projectRoot !== toolsProjectRoot) continue;
66
+ toolsResults.push([configFile, { projects: { [projectRoot]: { targets: { [targetName]: {
67
+ executor: `${PLUGIN_NAME}:publish-placeholder`,
68
+ options: {}
69
+ } } } } }]);
70
+ continue;
71
+ }
72
+ if (options.packageTargets === false) continue;
73
+ if (!publishablePackageName(normalized, context.workspaceRoot)) continue;
74
+ publishableManifests += 1;
75
+ if (exclude.some((prefix) => projectRoot === prefix || projectRoot.startsWith(`${prefix}/`))) continue;
76
+ packageResults.push([configFile, { projects: { [projectRoot]: { targets: { [targetName]: {
41
77
  executor: `${PLUGIN_NAME}:publish-placeholder`,
42
- options: {}
78
+ options: { packageJson: normalized }
43
79
  } } } } }]);
44
80
  }
45
- return results;
81
+ return publishableManifests > 0 ? packageResults : toolsResults;
46
82
  }];
47
83
  const plugin = {
48
84
  createNodesV2,
49
85
  name: PLUGIN_NAME
50
86
  };
51
87
  //#endregion
52
- export { createNodesV2, plugin as default, isReleaseBootstrapProject };
88
+ export { createNodesV2, plugin as default, isReleaseBootstrapProject, publishablePackageName };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx-devkit/prepare-for-release",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "license": "MIT",
5
5
  "private": false,
6
6
  "type": "module",
@@ -5,6 +5,10 @@
5
5
  "description": "Publishes a 0.0.0 placeholder tarball to the npm registry for every workspace package that is not yet published. Idempotent.",
6
6
  "type": "object",
7
7
  "properties": {
8
+ "packageJson": {
9
+ "type": "string",
10
+ "description": "Path to a single package.json (workspace-relative or absolute). When set, only that package is processed — used by the per-package `prepare-for-release` target."
11
+ },
8
12
  "scope": {
9
13
  "type": "array",
10
14
  "items": { "type": "string" },