Prepare your Meteor.js project for the big 3.0 release!
Tags: meteor, javascript, webdev
Published: 2023-11-01 11:04:21

Meteor.js 3.0 is an upcoming major release with lots of breaking changes. The platform is moving away from Fibers to use Node's native async await implementation.

In this article I'm going to show you a few techniques to detect code that requires changes in order to be ready for this upcoming Meteor.js 3.0 release. 🧙‍♂️

> <small>Photo by <a href="https://unsplash.com/@syinq?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Susan Q Yin</a> on <a href="https://unsplash.com/photos/people-sitting-on-white-concrete-stairs-Ctaj_HCqW84?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a></small>

Note, that this will not be a complete or perfect analysis, because you may end up with some false-positives or missing pieces. Consider it as a helping hand to aid the start for the transition. 🤝

**Another primary goal** is to be non-intrusive to your current application. This means, there should be no breaking effect to your current application by implementing the techniques, presented in this article.

This is important, because any breaking effect (server crashes etc.) creates frustration and decreases the chance of people finally starting to migrate now.

## Background / why this is important? ☝

If you know all about Meteor.js 3.0 then you can safely skip this section.

Meteor.js is around for [over 10 years](https://meteor10.sachagreif.com/) now, and it's core API-structure did not change significantly. I previously showed this in another [article on migrating an ancient Meteor.js project](https://dev.to/jankapunkt/reviving-an-ancient-meteorjs-project-in-10-minutes-30hl). 

However, while Meteor.js pioneered the fullstack technologies until about 2016 it eventually lost its amazing momentum in about 2017 ([read here](https://dev.to/jankapunkt/why-choose-meteor-or-not-for-your-next-project-1gnh) on the why and how).

The JavaScript ecosystem evolved and like in the cambrian explosion we saw a multitude of tools, frameworks and libraries emerging. 
A vast majority seemingly adopted the `async/await` pattern, 
while asynchronous code execution in Meteor.js was implemented using  [coroutines](https://en.wikipedia.org/wiki/Coroutine) via [Fibers](https://www.npmjs.com/package/fibers).

Finally, the release of Node 16 became basically incompatible with fibers and thus, Meteor.js got stuck on Node 14. This implied a [major rewrite of a large potion of the platform's internals](https://github.com/meteor/meteor/discussions/11505) as it all depended on `fibers`. Further, it implied that all Meteor.js projects and packages required a major rewrite as well. 

This is where **YOU** come into play.

## How do I know, if I need to migrate? 🤔

This answer is simple: you will have to! 🤓

This is, because all pre-3.0 projects run on a security-patched Node 14 ([read here](https://guide.meteor.com/using-node-v14.21.4) how to apply the patched version) and you will need Meteor 3.0 to be back on the safe side of the Node game by being able to use the latest Node LTS for your deployments.

## How do I know what to migrate? 🤔

This is a rather complex situation with no simple answer. There are basically three big parts of your codebase to review:

- Mongo Collection and Cursor usage
- Meteor Methods + Publications
- Meteor Packages that depend on the "old" code style

There is also an official list of core functionality that
is to be migrated. It's part of the ["How to migrate to Meteor Async in 2.x" guide](https://guide.meteor.com/prepare-meteor-3.0).

Each of these come with a different approach, different complexity and constraints. Implementation also varies, whether a static analysis is desired or if runtime analysis is okay, too. Let's take a look at each of them, one by one.

## Mongo Collection and Cursor usage 💽

In **classic mode** (using fibers) the Mongo collection calls to the MongoDB driver were executed within a Fiber and thus could be written in sync-style code, while being magically async under the hood:

```js
const document = collection.findOne({ foo: 'bar' })
```

In the new **async mode** (using async/await) we need to change this to an async counterpart:

```js
const document = await collection.findOneAsync({ foo: 'bar' })
```

This change targets the following `Mongo.Collection` methods:

| Class mode    | Async Mode         | Notes                 |
|---------------|--------------------|-----------------------|
| `insert`      | `insertAsync`      | on `Mongo.Collection` |
| `update`      | `updateAsync`      | on `Mongo.Collection` |
| `remove`      | `removeAsync`      | on `Mongo.Collection` |
| `findOne`     | `findOneAsync`     | on `Mongo.Collection` |
| `createIndex` | `createIndexAsync` | on `Mongo.Collection` |
| `count`       | `countAsync`       | on `Mongo.Cursor`     |
| `forEach`     | `forEachAsync`     | on `Mongo.Cursor`     |
| `map`         | `mapAsync`         | on `Mongo.Cursor`     |
| `fetch`       | `fetchAsync`       | on `Mongo.Cursor`     |

> Additional info

Note, that `Cursor.count` is deprecated and you should consider migrating to [`Collection.countDocuments`](https://docs.meteor.com/api/collections.html#Mongo-Collection-countDocuments) or [`Collection.estimatedDocumentCount`](https://docs.meteor.com/api/collections.html#Mongo-Collection-estimatedDocumentCount).

### Static analysis 🔬

If you want to analyze their sync usage statically you would have to either write an [isobuild plugin](https://docs.meteor.com/api/packagejs.html#build-plugin-api) or a [babel plugin](https://babeljs.io/docs/plugins/).

The hardest challenge here is to get rid of the ambivalence due to the very common naming of the methods. For example: `forEach` and `map` are typical Array methods and may create lots of false-positives. You will likely have to track, if the variable.

> Additional Info

There seems to be [a discussion in the Meteor forums about an ESLINT plugin for static analysis](https://forums.meteor.com/t/meteor-3-0-async-functions-eslint-plugin/60738??utm_source=jkuester&utm_medium=online&utm_campaign=Q2-2022-Ambassadors). I suggest you to keep watching the topic, if this is an alternative to you.

### Runtime analysis 🔬

This approach is rather easy to implement and produces no false-positives. However, detection requires the code to run, which therefore requires a great test-coverage in order to really cover all possible calls. We can do that by **monkey patching** the methods mentioned above.

Big plus: we can also detect usage in dependent Meteor packages, if we make sure the pathing occurs before the package code runs on startup. This is fortunately very easy as you just need to follow these steps:

#### 1. Create a local package 📦

If your Meteor project does not contain a `packages` folder then you need to create one:

```shell
$ cd your-great-project
$ mkdir -p packages # needs to be on the same level as server, client, imports etc.
$ cd packages
```

Then you create a new local package with a unique name:

```shell
$ meteor create --package jkuester:migration-helper
$ cd ../ # back to project root
$ meteor add jkuester:migration-helper
```

Let's change the following method in **package.js** in order to **immediately execute the code** on startup (not to be confused with `Meteor.startup`, which runs **after** all startup code):

```js
Package.onUse(function (api) {
  api.versionsFrom('2.3')
  api.use('ecmascript')
  api.use('mongo')
  api.addFiles('migration-helper.js', 'server')
})
```

Finally, open the Meteor packages list at `your-great-project/.meteor/packages` and move the entry for the package **at the very top** of the file in order to apply the patches before any other package code runs.

#### 2. Create a new patch function 🔨

Stay in the package and edit the main file `migration-helper.js` which the following code (yes, you can copy/paste):

```js
import {Meteor} from 'meteor/meteor'
import {Mongo} from 'meteor/mongo'
import {ValidatedMethod } from 'meteor/mdg:validated-method'

// some common pattern
const newLine = /\n/g
const whiteSpace = /\s+/g

// return the current location
// of function execution, considering
// multiple levels of wrappers
const getLocation = () => {
  const e = new Error('')
  const lines = e.stack.split(newLine)
  return lines[3].replace(whiteSpace, ' ').trim()
}

// monkey-patch a Collection/Cursor proto function
// to inject some analysis code without altering
// the original behavior
const patch = (proto, name) => {
  const original = proto[name]
  const className = proto.constructor.name

  proto[name] = function (...args) {
    const self = this
    const location = getLocation()
    const isWrappedAsync = location.includes(`as ${name}Async`)

    if (!isWrappedAsync) {
      console.warn(`Deprecated: ${className}.${name} needs to be migrated to ${name}Async in collection "${self._name}"!`)
      console.warn('=>', location)
    }
    return original.call(self, ...args)
  }
}

// apply patching to Mongo.Collection functions
const mNames = ['insert', 'update', 'remove', 'findOne', 'createIndex']
const mProto = Mongo.Collection.prototype
mNames.forEach(name => patch(mProto, name))

// applying patches Mongo.Cursor functions
const cNames = ['count', 'forEach', 'map', 'fetch']
const cProto = Mongo.Cursor.prototype
cNames.forEach(name => patch(cProto, name))
```

Start your Meteor project or run your tests and look for the deprecation messages. You can also replace the `console.warn` with `throw new Error` to make the tests fail but that will also likely prevent your app from running - this is up to you how to handle things here.

## Meteor Methods ☄️

Most of the time you will define Methods and Publications statically on startup. This allows us to create a neat little tool that provides a summary of all our methods and publications.

Consider the following example, which inserts a new document into a Mongo.Collection (similar to what happens in the [Meteor tutorials](https://www.meteor.com/developers/tutorials)):

```js
// server/main.js

Meteor.methods({
  'createTodo' (text) {
    const userId = this
    const docId = TodosCollection.insert({ text, userId })
    return TodosCollection.findOne(docId)
  }
})
```

Building on top of the previous section, we continue to extend our migration helper package in order to detect the migration needs for this method. Let's start with Meteor Methods by patching the `Meteor.methods` function. You can continue in `migration-helper.js` by simply adding the following code at the end of the file:

```js
// ...continueing in migration-helper.js

const asyncLine = /\s*return Promise.asyncApply\(\(\) => {\n/g

// scans a function body for the above pattern
// to detect async functions
const analyze = ({ name, fn, location, type }) => {
  const source = fn.toString()
  const lines = source.split(byNewline)
  const isAsync = asyncLine.test(lines[1])

  if (!isAsync) {
    console.warn(`Deprecated (${type}): ${name} is not async, consider migrating now.`)
  }
}
```


> What is this actually good for? 

Let me explain: In Meteor.js 2.x (using Fibers) any async declared function gets recompiled by the [Meteor build tool](https://guide.meteor.com/build-tool.html), transforming async functions into this `Promise.asyncApply`. It basically connects the given function to a Fiber that keeps track of the execution stack.

In turn - every Method or Publication that is not transformed into this `Promise.asyncApply` will not contain this pattern on line 1. **Thus, we can detect that this function is not async yet.**

Let's apply this to `Meteor.methods`; you can simply continue at the end of the file:

```js
// ...continueing in migration-helper.js

const originalMethods = Meteor.methods

Meteor.methods = options => {
  const location = getLocation()
  const entries = Object.entries(options)
  const type = 'Method'
  entries.forEach(([name, fn]) => {
    analyze({ name, fn, location, type })
  })

  return originalMethods(options)
}
```

Restarting the project yields to the following output:

```shell
W20231102-15:28:12.775(1)? (STDERR) Deprecated (Method): createTodo is not async, consider migrating now.
W20231102-15:28:12.776(1)? (STDERR)   => at module (server/main.js:15:8)
```

And during tests or runtime we will see a message like this:

```js
W20231102-15:32:31.550(1)? (STDERR) Deprecated: Collection.insert needs to be migrated to insertAsync in collection "todos"!
W20231102-15:32:31.551(1)? (STDERR) => at Collection.Mongo.Collection.<computed> [as insertAsync] (packages/mongo/collection.js:1004:46)
W20231102-15:32:31.560(1)? (STDERR) Deprecated: Collection.findOne needs to be migrated to findOneAsync in collection "todos"!
W20231102-15:32:31.561(1)? (STDERR) => at MethodInvocation.createTodo (server/main.js:26:28)
```

Both indicating the `createTodo` method needs some migration efforts. Let's do that:

```js
Meteor.methods({
  'createTodo': async function (text) {
    const userId = this
    const docId = await TodosCollection.insertAsync({ text, userId })
    return TodosCollection.findOneAsync(docId)
  }
})
```

The warnings are gone and you have safely prepared this method for the major 3.0 update.

## Meteor Publications ☄️

If you have already implemented the functions from the Meteor Methods section before then patching publications is as easy as it can get:

```js
const originalPub = Meteor.publish

Meteor.publish = (name, fn) => {
  const location = getLocation()
  const type = 'Publication'
  analyze({ name, fn, location, type })
  return originalPub(name, fn)
}
```

Note, that publications return cursors using `.find` which does not need to be migrated to async. Therefore this may create some false-positives for functions that use no other Mongo.Collection or Mongo.Cursor functions that have to be async.

## Validated Methods ☄️

A special case is, when using `ValidatedMethod` via `mdg:validated-method`. If you don't know the package, I highly suggest to check it out as [it's the recommended way (add guide link)]() to create method with builtin argument validation.

We will not be able to detect non-async methods passed to the `ValidatedMethod` constructor as with the `Meteor.methods` pattern, described above. This is, because we basically can't override/monkey-patch an ES6 constructor function the same way we do with any other function.

Fortunately we still have two alternative ways for detection.

### Detect using a mixin 🔍

This works by creating a mixin function that detects the `options.run` function the same way we detect the `Meteor.methods`. However, there is one disadvantage - you have to assign the mixin to every `ValidatedMethod` construction options and at that point you'll likely check each method manually.

Therefore, this approach makes only sense if you use a factory-function to create your Methods, which acts as a single point of construction. In that case, it's rather easy to inject the mixin into your validated methods:

```js
export const createMethod = options => {
  options.mixins = options.mixins ?? []
  options.mixins.push(checkAsyncMixin)
  return new ValidatedMethod(options)
}

const checkAsyncMixin = options => {
  const { name, run } = options
  analyze({
    name: name,
    location: getLocation(),
    type: 'ValidatedMethod',
    fn: run
  })
  return options
}
```

### Detect at runtime 🔬

If you don't use a pattern, similar to the above-mentioned factory-function, then you still have one more option here. However, this will only detect the methods at runtime, and you will either have to have a decent test-coverage or other ways to make sure that every of your methods are called.

It works by overriding the `_execute` prototype method, which will run on every method invocation for methods, declared using `ValidatedMethod`:

```js
const originalExec = ValidatedMethod.prototype._execute

ValidatedMethod.prototype._execute = function (...args) {
  const self = this

  analyze({
    name: self.name,
    location: getLocation(),
    type: 'ValidatedMethod',
    fn: self.run
  })
  return originalExec.call(self, ...args)
}
```

## Summary and outlook 🔭

I showed in this article how to easily detect parts of your Meteor 2.x server environment that need change in order to be 3.0-ready. I purposefully leaved out the client side as this easily exceeds the scope of a short and simple article. 

Since Meteor.js supports many client side libraries and frameworks this may be subject to specific articles for each of them, and I encourage everyone to step up and start writing on their experience
with them.

You can use this code and refactor / modify it to your needs or simply use the package `jkuester:migration-helper`.
It's listed on Packosphere and available on GitHub, too:

### Packosphere Link 📦

{% embed https://packosphere.com/jkuester/migration-helper %}

### GitHub repository ⌨️

{% github https://github.com/jankapunkt/meteor-migration-helper %}

---
## About me 👋

I regularly publish articles here on dev.to about **Meteor.js** and **JavaScript**. Recently I also co-host the [weekly Meteor.js community podcast](https://www.youtube.com/@meteorjscommunity), which contains the newest from Meteor.js and the community.

You can also find (and contact) me on [GitHub](https://github.com/jankapunkt/), [Twitter/X](https://twitter.com/kuester_jan) and [LinkedIn](https://www.linkedin.com/in/jan-kuester/).

If you like what you are reading and want to support me, you can [sponsor me on GitHub](https://github.com/jankapunkt), [send me a tip via PayPal](https://paypal.me/kuesterjan) or sponsor me a book form [my Amazon wishlist](https://www.amazon.de/-/en/hz/wishlist/ls/12YMIY0QNH9TK?ref_=list_d_wl_lfu_nav_1).