Files
tspublish/readme.md

11 KiB
Raw Blame History

@git.zone/tspublish 🚀

Effortlessly publish multiple TypeScript packages from your monorepo

npm version License: MIT

🌟 What is tspublish?

@git.zone/tspublish is your Swiss Army knife for managing and publishing multiple TypeScript packages from a monorepo. It automates the tedious parts of package publishing while giving you full control over the process. Whether you're maintaining a suite of microservices, a component library, or any collection of related packages, tspublish makes your life easier.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Key Features

  • 📦 Automatic Package Discovery - Scans your monorepo for publishable packages
  • 🎨 Beautiful CLI Output - Color-coded logging with progress indicators
  • 🔍 Version Collision Detection - Prevents accidental overwrites
  • 🏗️ Build Integration - Automatically builds TypeScript before publishing
  • 🎯 Smart Dependency Management - Inherits dependencies from your monorepo
  • 🌐 Multi-Registry Support - Publish to npm, GitHub packages, or private registries
  • Zero Config - Works out of the box with sensible defaults

📥 Installation

# Using pnpm (recommended)
pnpm add -D @git.zone/tspublish

# Using npm
npm install --save-dev @git.zone/tspublish

# Using yarn
yarn add -D @git.zone/tspublish

Global Installation

npm install -g @git.zone/tspublish

🚀 Quick Start

1 Structure Your Monorepo

Organize your packages with the ts prefix convention:

my-awesome-monorepo/
├── package.json          # Main monorepo package.json
├── tsconfig.json         # Shared TypeScript config
├── ts-core/              # Core package
│   ├── ts/               # TypeScript source files
│   ├── readme.md         # Package documentation
│   └── tspublish.json    # Publishing configuration
├── ts-utils/             # Utilities package
│   ├── ts/
│   ├── readme.md
│   └── tspublish.json
└── ts-cli/               # CLI package
    ├── ts/
    ├── readme.md
    └── tspublish.json

2 Configure Each Package

Create a tspublish.json in each package directory:

{
  "name": "@myorg/core",
  "order": 1,
  "dependencies": [
    "@push.rocks/smartpromise",
    "@push.rocks/smartfile"
  ],
  "registries": [
    "registry.npmjs.org:public",
    "npm.pkg.github.com:private"
  ],
  "bin": ["my-cli"]
}

Configuration Options

Field Type Description
name string Package name (required)
order number Build order for interdependent packages
dependencies string[] Dependencies from the monorepo to include
registries string[] Target registries with access level
bin string[] CLI executable names

3 Run the Publisher

Command Line

# From your monorepo root
npx tspublish

Programmatic Usage

import { TsPublish } from '@git.zone/tspublish';

const publisher = new TsPublish();
await publisher.publish(process.cwd());

🎯 Advanced Usage

Custom Publishing Pipeline

import { TsPublish, PublishModule } from '@git.zone/tspublish';

// Initialize the publisher
const publisher = new TsPublish();

// Get all publishable modules
const modules = await publisher.getModuleSubDirs('./my-monorepo');

// Custom processing for each module
for (const [name, config] of Object.entries(modules)) {
  const module = new PublishModule(publisher, {
    monoRepoDir: './my-monorepo',
    packageSubFolder: name
  });
  
  // Initialize module
  await module.init();
  
  // Create publish directory
  await module.createPublishModuleDir();
  
  // Custom build step
  console.log(`Building ${config.name}...`);
  await module.build();
  
  // Publish to registries
  await module.publish();
}

Registry Configuration

TSPublish supports multiple registries with different access levels. You have three approaches:

1 Explicit Registries

Define specific registries directly in your tspublish.json:

{
  "registries": [
    "registry.npmjs.org:public",        // Public npm package
    "npm.pkg.github.com:private",       // Private GitHub package
    "my-company.jfrog.io/npm:restricted" // Corporate registry
  ]
}

2 Use Base Configuration (useBase)

Inherit registries from your project's npmextra.json configuration (managed by gitzone config):

{
  "registries": ["useBase"]
}

This reads from npmextra.json under @git.zone/cli.release.registries.

3 Extend Base Configuration (extendBase)

Start with base registries and add/remove specific ones:

{
  "registries": [
    "extendBase",
    "custom-registry.example.com:public",
    "-https://registry.npmjs.org"  // Exclude this registry
  ]
}

The - prefix excludes a registry from the base configuration.

Empty Registries

If no registries are configured, the package will be built but not published (a warning is logged).

Build Order Management

When packages depend on each other, use the order field to ensure correct build sequence:

// ts-core/tspublish.json
{
  "name": "@myorg/core",
  "order": 1,
  "dependencies": []
}

// ts-utils/tspublish.json
{
  "name": "@myorg/utils",
  "order": 2,
  "dependencies": ["@myorg/core"]
}

CLI Binary Configuration

For packages that include CLI tools:

{
  "name": "@myorg/cli",
  "bin": ["my-cli", "my-tool"],
  "dependencies": ["commander", "chalk"]
}

This automatically generates the necessary cli.js wrapper and configures the package.json bin field.

🎨 Beautiful Output

TSPublish provides rich, colored console output with:

  • 📊 Progress bars for multi-package operations
  • 🎯 Clear status indicators ( info, ✓ success, ⚠ warning, ✖ error)
  • 📦 Package-specific icons and formatting
  • 🚀 Visual separators between operation phases

🔧 How It Works

  1. Discovery Phase 🔍

    • Scans for directories starting with ts
    • Validates tspublish.json presence
    • Orders packages by dependency
  2. Preparation Phase 📋

    • Creates temporary dist_publish_* directories
    • Generates package.json from tspublish.json
    • Copies source files and assets
    • Sets up TypeScript configuration
  3. Build Phase 🔨

    • Runs TypeScript compilation
    • Generates declaration files
    • Prepares distribution bundle
  4. Validation Phase

    • Checks npm registry for existing versions
    • Prevents accidental overwrites
    • Validates package metadata
  5. Publishing Phase 🚀

    • Publishes to configured registries
    • Handles authentication
    • Reports success/failure

🤝 Integration with CI/CD

GitHub Actions

name: Publish Packages

on:
  push:
    tags:
      - 'v*'

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - uses: pnpm/action-setup@v2
        with:
          version: 8
          
      - uses: actions/setup-node@v3
        with:
          node-version: '20'
          cache: 'pnpm'
          
      - run: pnpm install
      
      - run: pnpm build
      
      - run: npx tspublish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

GitLab CI

publish:
  stage: deploy
  image: node:20
  before_script:
    - npm install -g pnpm
    - pnpm install
  script:
    - pnpm build
    - npx tspublish
  only:
    - tags

📚 API Reference

TsPublish Class

class TsPublish {
  // Publish all packages in a monorepo
  async publish(monorepoDirPath: string): Promise<void>
  
  // Get all publishable module configurations
  async getModuleSubDirs(dirPath: string): Promise<{[key: string]: ITsPublishJson}>
}

PublishModule Class

class PublishModule {
  // Initialize the module for publishing
  async init(): Promise<void>
  
  // Create the publishing directory structure
  async createPublishModuleDir(): Promise<void>
  
  // Build the TypeScript package
  async build(): Promise<void>
  
  // Publish to configured registries
  async publish(): Promise<void>
}

ITsPublishJson Interface

interface ITsPublishJson {
  name: string           // Package name
  order: number          // Build order
  dependencies: string[] // Dependencies to include
  registries: string[]   // Target registries
  bin: string[]         // CLI binaries
}

🐛 Troubleshooting

Common Issues

Package already exists with version X.X.X

  • TSPublish detected a version collision
  • Update your monorepo's package.json version
  • Or unpublish the existing version if appropriate

No publish modules found

  • Ensure your packages follow the ts-* naming convention
  • Check that each package has a valid tspublish.json

Build failures

  • Verify TypeScript configuration
  • Check that all dependencies are installed
  • Review the build output for specific errors

useBase/extendBase error

  • Ensure your npmextra.json has registries configured at @git.zone/cli.release.registries
  • Use gitzone config add <registry-url> to configure base registries

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.