npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@blend-col/cdk-pipeline-construct

v1.1.1

Published

AWS CDK Pipeline Construct - both as a library and standalone app

Readme

CDK Pipeline Construct

Un constructo AWS CDK reutilizable que simplifica la creación de pipelines CI/CD con integración GitHub, soporte para múltiples tipos de aplicaciones y despliegue opcional.

✨ Características

  • 🔄 Dual Functionality: Funciona como librería npm reutilizable y como aplicación CDK independiente
  • 🔗 GitHub Integration: Integración nativa con GitHub vía CodeStar Connections (sin OAuth)
  • 🚀 Multiple Pipeline Types: Soporte para fargate, s3Static, y generic
  • 📦 BuildSpecs Inline: BuildSpecs definidos como objetos TypeScript (no archivos YAML externos)
  • 🎯 Optional Deploy: Etapa de deploy completamente opcional
  • 🛡️ Security First: Roles IAM granulares y permisos mínimos necesarios
  • 🧪 Fully Tested: Suite completa de tests unitarios con Jest

📋 Prerequisitos

  • AWS CLI configurado
  • Node.js v16 o superior
  • AWS CDK v2
  • Una conexión CodeStar configurada para GitHub

🚀 Inicio Rápido

Como Librería NPM

npm install cdk-pipeline-construct
import { PipelineConstruct } from 'cdk-pipeline-construct';
import * as ecr from 'aws-cdk-lib/aws-ecr';

// Crear ECR para pipeline tipo Fargate
const ecrRepo = new ecr.Repository(this, 'MyAppRepo', {
  repositoryName: 'my-app'
});

// Crear el pipeline
const pipeline = new PipelineConstruct(this, 'MyPipeline', {
  namespace: 'MyApp',
  pipelineType: 'fargate',
  ecrRepository: ecrRepo,
  sourceConfig: {
    owner: 'tu-organizacion',
    repo: 'tu-repositorio', 
    branch: 'main',
    connectionArn: 'arn:aws:codeconnections:region:account:connection/id'
  },
  buildConfig: {
    privileged: true, // Requerido para Docker
    environmentVariables: {
      NODE_ENV: { value: 'production' }
    }
  },
  // deployConfig es opcional
  deployConfig: {
    environmentVariables: {
      ECS_SERVICE_NAME: { value: 'my-service' }
    }
  }
});

Como Aplicación CDK

git clone <este-repositorio>
cd cdk-pipeline-construct

# Instalar dependencias
npm install
npm run build

# Configurar tu pipeline en stacks/pipeline-stack.ts
npm run synth   # Sintetizar templates CloudFormation
npm run deploy  # Desplegar infraestructura
npm run diff    # Ver cambios pendientes

Arquitectura del constructo

El constructo tiene la siguiente infraestructura:

Arquitectura del constructo

En esta se observa que se parte de los roles que permiten al pipeline ejecutarse, adicionalmente de los necesarios en la fase de build y deploy. Se tiene el pipeline que se activa ante los eventos de push en la rama indicada y esto as su vez permite que se ejecuten los pasos de construcción y opcionalmente el de despliegue.

🏗️ Tipos de Pipeline

Fargate Pipeline

Para aplicaciones containerizadas que se despliegan en AWS Fargate:

new PipelineConstruct(this, 'FargatePipeline', {
  namespace: 'MyFargateApp',
  pipelineType: 'fargate',
  ecrRepository: ecrRepo, // ⚠️ Requerido para tipo fargate
  sourceConfig: { /* ... */ },
  buildConfig: {
    privileged: true, // ✅ Habilitado automáticamente para fargate
    // BuildSpec por defecto incluye:
    // - Login a ECR
    // - Build de imagen Docker  
    // - Push a ECR con tags latest y build number
  },
  deployConfig: {
    // BuildSpec por defecto para deploy ECS
    // Puedes sobrescribir con tu lógica de deploy
  }
});

S3 Static Website Pipeline

Para sitios web estáticos (React, Vue, Angular, etc.):

new PipelineConstruct(this, 'StaticSitePipeline', {
  namespace: 'MyWebsite',
  pipelineType: 's3Static',
  sourceConfig: { /* ... */ },
  buildConfig: {
    // BuildSpec por defecto para build web apps
    environmentVariables: {
      NODE_ENV: { value: 'production' }
    }
  },
  deployConfig: {
    environmentVariables: {
      S3_BUCKET: { value: 'my-website-bucket' },
      CLOUDFRONT_DISTRIBUTION_ID: { value: 'E1234567890' }
    }
    // BuildSpec por defecto incluye S3 sync y CloudFront invalidation
  }
});

Generic Pipeline

Para casos de uso personalizados:

new PipelineConstruct(this, 'GenericPipeline', {
  namespace: 'MyApp',
  pipelineType: 'generic', // o omitir (es el default)
  sourceConfig: { /* ... */ },
  buildConfig: {
    buildSpec: BuildSpec.fromObject({
      version: 0.2,
      phases: {
        build: {
          commands: [
            'echo "Construyendo mi aplicación personalizada"',
            'npm install',
            'npm run build',
            'npm test'
          ]
        }
      }
    })
  },
  // deployConfig es completamente opcional
});

⚙️ Configuración Avanzada

BuildSpecs Personalizados

Los BuildSpecs se definen como objetos TypeScript para mayor flexibilidad:

import { BuildSpec } from 'aws-cdk-lib/aws-codebuild';

const customBuildSpec = BuildSpec.fromObject({
  version: 0.2,
  phases: {
    pre_build: {
      commands: [
        'echo Autenticando con servicios externos...'
      ]
    },
    build: {
      commands: [
        'npm ci',
        'npm run lint',
        'npm run test:ci',
        'npm run build'
      ]
    },
    post_build: {
      commands: [
        'echo Build completado exitosamente',
        'ls -la dist/'
      ]
    }
  },
  artifacts: {
    files: ['**/*'],
    'base-directory': 'dist'
  }
});

new PipelineConstruct(this, 'CustomPipeline', {
  // ...
  buildConfig: {
    buildSpec: customBuildSpec
  }
});

Variables de Entorno

Variables automáticas disponibles en todos los builds:

AWS_ACCOUNT_ID      # ID de cuenta AWS
AWS_DEFAULT_REGION  # Región de deploy
NAMESPACE           # Namespace del pipeline
PIPELINE_NAME       # Nombre del pipeline
PIPELINE_EXECUTION_ID # ID único de ejecución

# Para tipo 'fargate':
ECR_REPOSITORY_URI  # URI completo del repo ECR
ECR_REGISTRY        # Registry ECR (sin repo name)

Configuración de Bucket de Artefactos

new PipelineConstruct(this, 'Pipeline', {
  // ...
  artifactBucketConfig: {
    bucketName: 'mi-bucket-personalizado',
    removalPolicy: RemovalPolicy.RETAIN,
    encryption: true // default: true
  }
});

Deploy Opcional

La etapa de deploy es completamente opcional:

// Pipeline solo con build (sin deploy)
new PipelineConstruct(this, 'BuildOnlyPipeline', {
  namespace: 'BuildOnly',
  sourceConfig: { /* ... */ },
  buildConfig: { /* ... */ }
  // Sin deployConfig = sin etapa de deploy
});

📚 Ejemplos Completos

Revisa la carpeta examples/ para casos de uso específicos:

🧪 Testing

npm test                # Ejecutar todos los tests
npm test -- --watch     # Modo watch
npm test -- --coverage  # Con cobertura

Comandos disponibles:

  • npm run build - Compilar TypeScript
  • npm run watch - Compilar en modo watch
  • npm run synth - Sintetizar templates CloudFormation
  • npm run deploy - Desplegar a AWS
  • npm run diff - Ver cambios pendientes
  • npm run destroy - Eliminar stack

🔧 Desarrollo

# Configuración inicial
npm install

# Build
npm run build

# Desarrollo con watch
npm run watch

# Testing
npm test                # Ejecutar todos los tests
npm test -- --watch     # Modo watch
npm test -- --coverage  # Con cobertura

# Como aplicación CDK de ejemplo
npm run synth   # Sintetizar CloudFormation templates
npm run deploy  # Desplegar a AWS
npm run diff    # Ver cambios pendientes
npm run destroy # Eliminar stack

📖 API Reference

PipelineConstructProps

| Propiedad | Tipo | Requerido | Descripción | |-----------|------|-----------|-------------| | namespace | string | ✅ | Prefijo para nombrar recursos | | sourceConfig | SourceConfig | ✅ | Configuración de fuente GitHub | | buildConfig | BuildConfig | ✅ | Configuración de la etapa build | | deployConfig | DeployConfig | ❌ | Configuración de la etapa deploy | | pipelineType | 'fargate' \| 's3Static' \| 'generic' | ❌ | Tipo de pipeline (default: 'generic') | | ecrRepository | ecr.IRepository | ⚠️ | Requerido solo para tipo 'fargate' | | pipelineName | string | ❌ | Nombre personalizado del pipeline | | artifactBucketConfig | ArtifactBucketConfig | ❌ | Configuración del bucket S3 | | tags | { [key: string]: string } | ❌ | Tags para todos los recursos |

SourceConfig

| Propiedad | Tipo | Requerido | Descripción | |-----------|------|-----------|-------------| | owner | string | ✅ | Propietario del repositorio GitHub | | repo | string | ✅ | Nombre del repositorio | | branch | string | ✅ | Rama a monitorear | | connectionArn | string | ✅ | ARN de CodeStar Connection | | triggerOnPush | boolean | ❌ | Trigger automático (default: true) |

Revisa src/types.ts para la documentación completa de la API.

🚦 Recursos Creados

El constructo crea los siguientes recursos AWS:

  • CodePipeline: Pipeline principal con etapas Source, Build y Deploy (opcional)
  • CodeBuild Projects: Proyectos para build y deploy con roles IAM específicos
  • S3 Bucket: Bucket de artefactos con cifrado y lifecycle policy
  • IAM Roles: Roles granulares para pipeline, source, build y deploy
  • CloudWatch Logs: Logs automáticos para todas las ejecuciones

🔒 Seguridad

  • Roles IAM Granulares: Cada componente tiene permisos mínimos necesarios
  • No OAuth: Usa CodeStar Connections (más seguro que OAuth apps)
  • Cifrado por Defecto: Bucket de artefactos cifrado por defecto
  • Acceso Limitado: Solo los recursos necesarios tienen acceso a ECR/S3

🆘 Troubleshooting

Error: "ECR repository is required for Fargate pipeline type"

// ❌ Incorrecto - falta ECR para tipo fargate
new PipelineConstruct(this, 'Pipeline', {
  pipelineType: 'fargate' // Sin ecrRepository
});

// ✅ Correcto
const ecrRepo = new ecr.Repository(this, 'Repo');
new PipelineConstruct(this, 'Pipeline', {
  pipelineType: 'fargate',
  ecrRepository: ecrRepo // ✅ Proporcionado
});

Error de Permisos CodeStar

Verifica que la conexión CodeStar esté activa y tenga permisos para el repositorio:

aws codeconnections get-connection --connection-arn your-connection-arn

Builds Fallando por Dependencias

Para paquetes privados, configura variables de entorno para autenticación:

buildConfig: {
  environmentVariables: {
    // Ejemplo: variables para autenticación personalizada
  }
}

cdk destroy