|
| 1 | +#!/usr/bin/env zx |
| 2 | +import 'zx/globals'; |
| 3 | + |
| 4 | +// Type declaration for process (zx doesn't include Node.js types) |
| 5 | +declare const process: { |
| 6 | + env: Record<string, string | undefined>; |
| 7 | + cwd: () => string; |
| 8 | + argv: string[]; |
| 9 | + exit: (code: number) => never; |
| 10 | +}; |
| 11 | + |
| 12 | +/** |
| 13 | + * Publish a single package to npm if needed |
| 14 | + * |
| 15 | + * This script: |
| 16 | + * - Operates on the current workspace directory |
| 17 | + * - Checks npm registry before publishing |
| 18 | + * - Skips private packages automatically |
| 19 | + * |
| 20 | + * Usage: |
| 21 | + * # In a workspace directory: |
| 22 | + * npx zx publish-package-if-needed.mts # Publish for real |
| 23 | + * npx zx publish-package-if-needed.mts --dry-run # Simulate publishing |
| 24 | + * |
| 25 | + * # For all workspaces in topological order: |
| 26 | + * yarn workspaces foreach --all --topological --no-private \ |
| 27 | + * exec npx zx .github/scripts/publish-package-if-needed.mts |
| 28 | + */ |
| 29 | + |
| 30 | +// Parse command line arguments |
| 31 | +const isDryRun = process.argv.includes('--dry-run'); |
| 32 | + |
| 33 | +// Read package.json from current directory |
| 34 | +const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf-8')); |
| 35 | +const { name, version, private: isPrivate } = packageJson; |
| 36 | + |
| 37 | +// Skip private packages |
| 38 | +if (isPrivate) { |
| 39 | + echo(`⊘ Skipping private package: ${name}`); |
| 40 | + process.exit(0); |
| 41 | +} |
| 42 | + |
| 43 | +// Check if package@version already exists on npm |
| 44 | +const result = await $`npm view ${name}@${version} version 2>&1`.nothrow().quiet(); |
| 45 | +const shouldPublish = result.exitCode !== 0 || result.stdout.trim() !== version; |
| 46 | + |
| 47 | +if (!shouldPublish) { |
| 48 | + echo(`✓ Already published: ${name}@${version}`); |
| 49 | + process.exit(0); |
| 50 | +} |
| 51 | + |
| 52 | +// Publish the package |
| 53 | +const startMsg = isDryRun ? 'Simulating publish' : 'Publishing'; |
| 54 | +const endMsg = isDryRun ? 'Dry-run successful for' : 'Successfully published'; |
| 55 | + |
| 56 | +echo(`→ ${startMsg}: ${name}@${version}`); |
| 57 | + |
| 58 | +const publishCmd = isDryRun |
| 59 | + ? $`yarn npm publish --access public --dry-run` |
| 60 | + : $`yarn npm publish --access public`; |
| 61 | + |
| 62 | +await publishCmd; |
| 63 | +echo(`✓ ${endMsg}: ${name}@${version}`); |
0 commit comments