Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 60 additions & 0 deletions recipes/timers-deprecations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Node.js Timers Deprecations

This recipe migrates deprecated internals from `node:timers` to the supported public timers API. It replaces usages of `timers.enroll()`, `timers.unenroll()`, `timers.active()`, and `timers._unrefActive()` with standard constructs built on top of `setTimeout()`, `clearTimeout()`, and `Timer#unref()`.

See the upstream notices: [DEP0095](https://nodejs.org/api/deprecations.html#DEP0095), [DEP0096](https://nodejs.org/api/deprecations.html#DEP0096), [DEP0126](https://nodejs.org/api/deprecations.html#DEP0126), and [DEP0127](https://nodejs.org/api/deprecations.html#DEP0127).

## Example

### Replace `timers.enroll()`

**Before:**

```js
const timers = require('node:timers');
const resource = { _idleTimeout: 1500 };
timers.enroll(resource, 1500);
```

**After:**

```js
const resource = { timeout: setTimeout(() => {
// timeout handler
}, 1500) };
```

### Replace `timers.unenroll()`

**Before:**

```js
timers.unenroll(resource);
```

**After:**

```js
clearTimeout(resource.timeout);
```

### Replace `timers.active()` and `timers._unrefActive()`

**Before:**

```js
const timers = require('node:timers');
timers.active(resource);
timers._unrefActive(resource);
```

**After:**

```js
const handle = setTimeout(onTimeout, delay);
handle.unref();
```

## Caveats

The legacy APIs exposed internal timer bookkeeping fields such as `_idleStart` or `_idleTimeout`. Those internals have no public equivalent. The codemod focuses on migrating the control flow to modern timers and leaves application specific bookkeeping to the developer. Carefully review the transformed code to ensure that any custom metadata is still updated as expected.
21 changes: 21 additions & 0 deletions recipes/timers-deprecations/codemod.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
schema_version: "1.0"
name: "@nodejs/timers-deprecations"
version: 1.0.0
description: Migrate deprecated node:timers APIs to public timer functions.
author: Augustin Mauroy
license: MIT
workflow: workflow.yaml
category: migration

targets:
languages:
- javascript
- typescript

keywords:
- migration
- timers

registry:
access: public
visibility: public
29 changes: 29 additions & 0 deletions recipes/timers-deprecations/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@nodejs/timers-deprecations",
"version": "1.0.0",
"description": "Migrate deprecated node:timers APIs to public timer functions.",
"type": "module",
"scripts": {
"test": "node --run test:enroll && node --run test:unenroll && node --run test:active && node --run test:unref && node --run test:imports",
"test:enroll": "npx codemod jssg test -l typescript ./src/enroll-to-set-timeout.ts ./tests/ --filter dep0095",
"test:unenroll": "npx codemod jssg test -l typescript ./src/unenroll-to-clear-timer.ts ./tests/ --filter dep0096",
"test:active": "npx codemod jssg test -l typescript ./src/active-to-standard-timer.ts ./tests/ --filter active",
"test:unref": "npx codemod jssg test -l typescript ./src/unref-active-to-unref.ts ./tests/ --filter unref",
"test:imports": "npx codemod jssg test -l typescript ./src/cleanup-imports.ts ./tests/ --filter imports"
},
"repository": {
"type": "git",
"url": "git+https://github.com/nodejs/userland-migrations.git",
"directory": "recipes/timers-deprecations",
"bugs": "https://github.com/nodejs/userland-migrations/issues"
},
"author": "Augustin Mauroy",
"license": "MIT",
"homepage": "https://github.com/nodejs/userland-migrations/tree/main/recipes/timers-deprecations#readme",
"devDependencies": {
"@codemod.com/jssg-types": "^1.0.9"
},
"dependencies": {
"@nodejs/codemod-utils": "*"
}
}
82 changes: 82 additions & 0 deletions recipes/timers-deprecations/src/active-to-standard-timer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { EOL } from 'node:os';
import {
getNodeImportStatements,
getNodeImportCalls,
} from '@nodejs/codemod-utils/ast-grep/import-statement';
import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call';
import { resolveBindingPath } from '@nodejs/codemod-utils/ast-grep/resolve-binding-path';
import {
findParentStatement,
isSafeResourceTarget,
} from '@nodejs/codemod-utils/ast-grep/general';
import {
detectIndentUnit,
getLineIndent,
} from '@nodejs/codemod-utils/ast-grep/indent';
import type { Edit, SgRoot } from '@codemod.com/jssg-types/main';
import type Js from '@codemod.com/jssg-types/langs/javascript';

const TARGET_METHOD = 'active';

export default function transform(root: SgRoot<Js>): string | null {
const rootNode = root.root();
const sourceCode = rootNode.text();
const indentUnit = detectIndentUnit(sourceCode);
const edits: Edit[] = [];
const handledStatements = new Set<number>();

const importNodes = [
...getNodeRequireCalls(root, 'timers'),
...getNodeImportStatements(root, 'timers'),
...getNodeImportCalls(root, 'timers'),
];

for (const importNode of importNodes) {
if (importNode.kind() === 'expression_statement') continue;
const bindingPath = resolveBindingPath(importNode, `$.${TARGET_METHOD}`);
if (!bindingPath) continue;

const matches = rootNode.findAll({
rule: {
any: [
{ pattern: `${bindingPath}($RESOURCE)` },
{ pattern: `${bindingPath}($RESOURCE, $$$REST)` },
],
},
});

for (const match of matches) {
const resourceNode = match.getMatch('RESOURCE');
if (!resourceNode) continue;

if (!isSafeResourceTarget(resourceNode)) continue;

const statement = findParentStatement(match);
if (!statement) continue;

if (handledStatements.has(statement.id())) continue;
handledStatements.add(statement.id());

const indent = getLineIndent(sourceCode, statement.range().start.index);
const resourceText = resourceNode.text();
const childIndent = indent + indentUnit;
const innerIndent = childIndent + indentUnit;

const replacement =
`if (${resourceText}.timeout != null) {${EOL}` +
`${childIndent}clearTimeout(${resourceText}.timeout);${EOL}` +
`${indent}}${EOL}${EOL}` +
`${indent}${resourceText}.timeout = setTimeout(() => {${EOL}` +
`${childIndent}if (typeof ${resourceText}._onTimeout === "function") {${EOL}` +
`${innerIndent}${resourceText}._onTimeout();${EOL}` +
`${childIndent}}${EOL}` +
`${indent}}, ${resourceText}._idleTimeout);`;

edits.push(statement.replace(replacement));
}
}

if (!edits.length) return null;

return rootNode.commitEdits(edits);
}
Loading
Loading