Easy Automatic npm Publishes

One common question from people using npm to publish, especially on CI systems, is how best to automate the process, especially when dealing with multiple branches.

For a while now, I've been using a pattern that takes almost all of the human interaction out of it, since I tend to mess stuff up when I type it with my fingers. This works well for automatic publishes from CI or when publishing manually from a terminal.

I haven't manually typed npm publish in a while, which is a good thing.

First things first, have good tests

I am a huge fan of running tests with 100% test coverage. It isn't a perfect guard against every problem out there, but it does keep me from doing stupid things, like assuming that I know what my program does.

My go-to test library is tap, but you can do this with any testing library that supports code coverage. If it doesn't support code coverage out of the box, you can use nyc to run any Node.js process with coverage tracking.

To use it, run npm i tap -D, and then add this to your scripts section in package.json:

{
  "scripts": {
    "test": "tap"
  },
  "tap": {
    "check-coverage": true
  }
}

The npm version Command

The npm version command will figure out what the next version should be, edit your package.json file, and even check it into git with a signed tag. The beauty of this is that it also prevents you from bumping the version when you have untracked changes in your git working directory, and provides some hook scripts that can do other things before or after the version bump.

In the scripts section of my package.json file, I add a preversion script that runs my tests:

{
  "scripts": {
    "preversion": "npm test",
    "test": "tap"
  },
  "tap": {
    "check-coverage": true
  }
}

Now, before I can bump the version, npm will make sure that my tests pass. If the test fails (or if coverage isn't 100%), then it'll fail and the version command fails.

Publishing on Version Change

Bumping the version is fine, but then it's time to share it. Along with preversion, the postversion command does actions after the version is bumped. So, let's hook onto that to publish the package.

{
  "scripts": {
    "postversion": "npm publish",
    "preversion": "npm test",
    "test": "tap"
  },
  "tap": {
    "check-coverage": true
  }
}

Keeping Git and npm in Sync

That's fine for pushing to npm, but then I have to remember to push the changes to git. (I have many times forgotten to do this, and gotten issues because the code on npm is not in GitHub, which is generally a bad sign.)

Thankfully, npm also gives us a way to hook a script around the publish event, so let's use that:

{
  "scripts": {
    "postpublish": "git push origin --all; git push origin --tags",
    "postversion": "npm publish",
    "preversion": "npm test",
    "test": "tap"
  },
  "tap": {
    "check-coverage": true
  }
}

This runs two commands. The first pushes all branches, and the second pushes all the tags (including my newly published version tag).

Branches and Dist-Tags

Occasionally, I'll find myself working on some big feature for a new release that is not yet ready for prime time.

In the feature branch, I'll modify the scripts by adding a --tag argument to the npm publish command to put it on a dist-tag other than latest.

{
  "scripts": {
    "postversion": "npm publish --tag=next",
    "postpublish": "git push origin --all; git push origin --tags",
    "preversion": "npm test",
    "test": "tap"
  },
  "tap": {
    "check-coverage": true
  }
}

Now, I can tell people to run npm install my-module@next to try out the new prerelease version.

On the other side, I might want to land a bugfix or backport a feature for a legacy version. To do that, I create a git branch with the old version, and update package.json to add a legacy tag instead.

{
  "scripts": {
    "postversion": "npm publish --tag=legacy",
    "postpublish": "git push origin --all; git push origin --tags",
    "preversion": "npm test",
    "test": "tap"
  },
  "tap": {
    "check-coverage": true
  }
}

Bonus Points: Sign Your Versions

Git has support for PGP signing tagged commits. To tell npm to take advantage of this, set these two config values:

npm config set sign-git-commit true
npm config set sign-git-tag true

If setting up PGP and hooking it up with Git is too much of a pain, you're not alone. I'm a nerd who's been computering for a very long time, and I can't handle it. Also, I'm always worried about my keys just sitting on my machine in text files, even if they are encrypted with a passphrase. And if they are encrypted with a passphrase, then I have to type it in all the time, and that's just too much work.

I'm a huge fan of Krypton. It stores your PGP and SSH private keys in your mobile device's secure storage vault, and then sends a push notification to allow it to do things with those keys. It's dead-simple to set up, and extremely easy to use, and gives you a hardware second factor for everything that matters.

Of course, and I don't exactly know if this is a bug or a feature, it does mean that whenever I run npm version, between the commit, the signature, the tag, and the two SSH connections, my phone does a lot of buzzing.

Running npm version to Test and Publish

From there, I use the npm version command to do all my publishing. For bug fixes, I run npm version patch. For new features, I run npm version minor. For breaking changes, I run npm version major.

If you use Conventional Commits or similar tools, you could even automate the detection of what kind of version bump it should be, though that's left as an exercise for the reader.

This approach of using npm scripts to automate the process works well with any system where you'll be publishing and committing. Set it up in your next project, and trust your human fingers a little bit less :)

PS: npm Configuration is Very Flexible

You'll note that I did --tag=<whatever> in the publish commands above. You can also configure npm in many other ways. Any configuration value (including tag in the case of npm publish) can be set:

  • explicitly on the command line, like --tag=whatever
  • in the environment, like NPM_CONFIG_TAG=whatever
  • in a .npmrc file in the root of your project, like tag = whatever
  • in a .npmrc file in your home directory
  • in /usr/local/etc/npmrc (or /usr/etc/npmrc on some systems).

This works inheritance-style, so the higher up on that list a setting is, the higher the priority.

For CI/CD systems, this means that you can sometimes set environment variables to control the behavior of npm commands, without having to change the code or inject files into places. If it's easier to control it with a file (for example, checking a .npmrc file into git), then that's also fine.

On Building npm and Hiring a CEO - Founders Talk

I had the opportunity to chat with Adam Stacoviak recently about the journey of creating npm and turning that into npm, Inc., 4 and a half years as CEO, and the transition to my new role as Chief Product Officer. Along the way, we touched on some of the long dark teatimes of the soul one goes through when contemplating handing your company over to a new leader, after pouring your heart into it for so long.

I hope you enjoy it.

Imgur - One hell of a rollercoaster ride

wow.

OSS, Risk, and Compliance

npmjs

I'm going to tell you a story.

There are no villains in this story. Just smart people doing their best, and unfortunately working at cross-purposes through no fault of their own.

The names and places have been changed, but it is a true story. I've heard this story a lot over the years in my role at npm.

Once Upon A Time...

Way back in the late 1900s, the once-successful ACME Corporation was falling behind. Their development of proprietary widgets (on a proprietary software stack) was unable to keep up with the competition, who were leveraging Open Source platforms at a much lower cost.

Many within ACME Corp wanted to adopt the OSS approach, but they were bound by a multitude of contracts and agreements with customers and the regulatory rules of the various countries in which ACME Corp operated.

ACME Corp was in a pickle. Over a barrel. Pickled in a barrel of mixed metaphors, one could say.

Accepting Open Source Software

Luckily, ACME Corp hit on a solution. They joined some of the foundations springing up to provide governance structures for popular OSS projects, and instituted a policy where any employee could use any Open Source code that they liked, provided it was submitted for review by their compliance team.

This allowed them to avoid projects that were abandoned, insecure, or published with an incompatible license. Using a simple form was all it took, their developers could deliver value using the most up to date methods and tools.

Life was good.

Then Life Changed

Shortly after the turn of the 21st century, a series of well-intended solutions to valid problems ended up causing new problems for ACME Corp. All solutions, in solving a problem, reveal new ones.

First, GitHub made it far easier for developers of Open Source to collaborate with one another. This allowed projects to become quite popular without any corporate or nonprofit backing.

Next, Node.js brought JavaScript out of the web browser. Prior to Node, plenty of Server-Side JS platforms had been hacked up as side projects, or funded projects of promising companies. But Node was the first to significantly benefit from GitHub's network effects.

The last piece of this puzzle was an early Node.js contributor, who'd been working in the SSJS space for a while, and decided to write a package manager. He'd seen the importance of package management as a development tool before, and had spent quite a bit of time thinking about how reducing friction makes great things happen.

Impacts

A simple module system and package methodology became ubiquitous. Suddenly JavaScript was easy to share and compose. Instead of JavaScript platforms having to include the kitchen sink, they could be lightweight toolkits with loose coupling between parts.

This reduction in friction enabled what came to be known as the "small modules" movement. A number of prolific Open Source enthusiasts began to conceive of a single file as the default unit of code sharing, instead of a branded platform backed by a foundation.

Meanwhile, back at ACME Corp...

With all this distributed sharing, instead of relying on 2 or 3 well-known OSS platforms with clear governance, web applications came to rely on an interconnected mesh of thousands of tiny modules, created by an unaffiliated horde of hundreds individual contributors.

At ACME Corp, the process has started to creak. Well, not "creak", exactly. More like "break". It's broken.

The compliance team insists on only using modules that pass review. Developers who do write hand-rolled scripts to catalog all of their dependencies for the requisition forms are laughed at.

"2305 modules? You've gotta be kidding me. Use less, or come back next year."

The best devs have moved on to companies with less stringent rules. New developers coming out of school don't even know how to create websites without npm and React and Babel and a zillion of these things.

Today, the battle lines are drawn within ACME Corp, forcing developers to rely on subterfuge. The cost of a security vulnerability or getting sued for violating a license can be in the millions. But failing to ship a website is an existential threat.

When compliance complains that the new continuous delivery system is circumventing their OSS rules, the CTO says "I know, I'm on it", and then quietly ignores it.

And they all lived happily ever after...?

I wish that this was pure fiction.

The approach to compliance in almost every industry has not kept up with the advances in Open Source Software practices. This is a pressing crisis facing some of the biggest software development teams in the world right now.

I believe this problem is solvable, but it is not adequately solved yet.

Most solutions ask an organization to choose between safety and efficiency; but inefficiency is never safe. The only valid approach is to reduce friction for development teams, while also helping compliance teams to do their job. This is the the only way to bring peace to the enterprise.

Will Happen, Happening, Happened - Rebecca Sugar

Time is an illusion that helps things make sense
So we are always living in the present tense
It seems unforgiving when a good thing ends
But you and I will always be back then
You and I will always be back then
You and I will always be back then
You and I will always be back then

Singing: Will happen, happening, happened
Will happen, happening, happened
And will happen again and again
Cause you and I will always be back then
You and I will always be back then
Will happen, happening, happened
Will happen, happening, happened
And we'll happen again and again
'Cause you and I will always be back then

If there was some amazing force outside of time
  to take us back to where we were
And hang each moment up like pictures on the wall
Inside a billion tiny frames so we can see it
  all, all, all

It would look like, will happen, happening, happened
Will happen, happening happened
And there we are again and again
'Cause you and I will always be back then
You and I will always be back then
Will happen, happening, happened
Will happen, happening, happened
And there we are again and again
'Cause you and I will always be back then
You and I will always be back then
You and I will always be back then
You and I will always be back then
That's why
You and I will always be best friends

I know rationally that Adventure Time is over. I saw it coming, and heard it rumored, and heard the wails of anguish over it from friends, and consumed by some unconscious fear of my own mourning, I slowed down watching the show, and gradually fell further and further behind.

The ending is waiting for me in the future, bittersweet and beautiful.

It will happen. Until then, Adventure Time is still happening.