@firefoxic/utils 2.1.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  [![License: MIT][license-image]][license-url]
4
4
  [![Changelog][changelog-image]][changelog-url]
5
- [![NPM version][npm-image]][npm-url]
6
5
  [![Test Status][test-image]][test-url]
7
6
 
8
7
  Collection of useful utilities for JavaScript and Node.js.
@@ -17,7 +16,7 @@ pnpm add -D @firefoxic/utils
17
16
 
18
17
  ### `getProjectRoot`
19
18
 
20
- Your action should set the `REPO_NAME` environment variable to the step you want. If your action works with pull requests, you should also add two lines (which are marked below with a special comment) to use the `PR_NUMBER` variable. For example:
19
+ Your action should set the `REPO_NAME` environment variable to the step you want. If your action works with pull requests, you should also add two lines (which are marked below with a special comment) to use the `PR_NUMBER` variable. For example:
21
20
 
22
21
  ```yaml
23
22
  jobs:
@@ -41,7 +40,7 @@ jobs:
41
40
  target-folder: ${{ github.event.pull_request.number }} # For PR action
42
41
  ```
43
42
 
44
- Than you can get the path to the project root when deploying to GitHub Pages, for example in `vite.config.js`:
43
+ Than you can get the path to the project root when deploying to GitHub Pages, for example in `vite.config.js`:
45
44
 
46
45
  ```js
47
46
  import { defineConfig } from "vite"
@@ -91,14 +90,54 @@ jobs:
91
90
  branch: gh-pages
92
91
  ```
93
92
 
93
+ ### `get-node-matrix`
94
+
95
+ A CLI utility that reads the `engines.node` field from the project's `package.json` and prints the minimum Node.js versions (as a JSON array) for use in a GitHub Actions matrix. When running in a GitHub Actions environment, it also appends `node_versions=...` to the file pointed to by `GITHUB_OUTPUT`.
96
+
97
+ Use it in the `discover` job of your workflow:
98
+
99
+ ```yaml
100
+ jobs:
101
+ discover:
102
+ runs-on: ubuntu-latest
103
+ outputs:
104
+ node_versions: ${{ steps.matrix.outputs.node_versions }}
105
+ steps:
106
+ - uses: actions/checkout@v7
107
+ - uses: pnpm/setup@v3
108
+ with:
109
+ cache: true
110
+ node-version: "26"
111
+ - id: matrix
112
+ run: pnpm dlx --package @firefoxic/utils get-node-matrix
113
+
114
+ test:
115
+ needs: discover
116
+ strategy:
117
+ fail-fast: false
118
+ matrix:
119
+ node: ${{ fromJSON(needs.discover.outputs.node_versions) }}
120
+ runs-on: ubuntu-latest
121
+ steps:
122
+ - uses: actions/checkout@v7
123
+ - uses: pnpm/setup@v3
124
+ with:
125
+ cache: true
126
+ runtime: node@${{ matrix.node }}
127
+ - run: make verify
128
+ ```
129
+
130
+ The utility resolves the project's `package.json` from the current working directory (walking up the directory tree), or from the `npm_package_json` environment variable when run through an npm/pnpm script.
131
+
132
+ By default it reads `engines.node` from the calling project's own `package.json`. Pass `--dependencies <package>` (or `--dependencies=<package>`, or the short form `-d <package>`) to also read it from dependencies — for example `--dependencies stylelint` to take the Node.js versions required by `stylelint` when it is installed as a dependency. Multiple packages can be passed as a comma-separated list: `--dependencies "stylelint,postcss"`. Versions from the project and all specified dependencies are merged into a single deduplicated list, keeping only the lowest version in each major line (e.g. `22.18.0` over `22.22.2`). If `engines.node` is missing everywhere, the utility fails with an error.
133
+
134
+ Pass `--help` or `-h` to show the CLI help message.
135
+
94
136
  [license-url]: https://github.com/firefoxic/utils/blob/main/LICENSE.md
95
137
  [license-image]: https://img.shields.io/badge/License-MIT-limegreen.svg
96
138
 
97
139
  [changelog-url]: https://github.com/firefoxic/utils/blob/main/CHANGELOG.md
98
140
  [changelog-image]: https://img.shields.io/badge/CHANGELOG-md-limegreen
99
141
 
100
- [npm-url]: https://www.npmjs.com/package/@firefoxic/utils
101
- [npm-image]: https://badge.fury.io/js/@firefoxic%2Futils.svg
102
-
103
142
  [test-url]: https://github.com/firefoxic/utils/actions
104
143
  [test-image]: https://github.com/firefoxic/utils/actions/workflows/test.yaml/badge.svg?branch=main
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ import { appendFileSync, readFileSync, statSync } from "node:fs";
3
+ import path from "node:path";
4
+ function resolvePackageJsonPath() {
5
+ let fromEnv = process.env.npm_package_json;
6
+ if (fromEnv) {
7
+ try {
8
+ if (statSync(fromEnv).isFile())
9
+ return fromEnv;
10
+ }
11
+ catch {
12
+ // Fall through to the directory search below.
13
+ }
14
+ }
15
+ let dir = path.resolve(process.cwd());
16
+ while (true) {
17
+ let candidate = path.resolve(dir, `package.json`);
18
+ try {
19
+ if (statSync(candidate).isFile())
20
+ return candidate;
21
+ }
22
+ catch {
23
+ // Keep walking up the directory tree.
24
+ }
25
+ let parent = path.dirname(dir);
26
+ if (parent === dir)
27
+ break;
28
+ dir = parent;
29
+ }
30
+ throw new Error(`Project package.json not found`);
31
+ }
32
+ function printHelp() {
33
+ process.stdout.write(`
34
+ Usage:
35
+ get-node-matrix [options]
36
+
37
+ Description:
38
+ Reads the engines.node field from package.json files
39
+ and prints the minimum Node.js versions as a JSON array
40
+ for use in a GitHub Actions matrix.
41
+ When running in GitHub Actions, the result is also appended
42
+ to the file pointed to by GITHUB_OUTPUT as node_versions=...
43
+
44
+ Options:
45
+ -d, --dependencies <packages>
46
+ Also read engines.node from the specified dependencies.
47
+ Multiple packages can be passed as a comma-separated list.
48
+ -h, --help
49
+ Show this help message and exit.
50
+
51
+ Examples:
52
+ get-node-matrix
53
+ get-node-matrix --dependencies stylelint
54
+ get-node-matrix -d "stylelint,postcss"
55
+ pnpm dlx --package @firefoxic/utils get-node-matrix -d stylelint
56
+
57
+ `);
58
+ process.exit(0);
59
+ }
60
+ function parseArgs() {
61
+ let dependencies = [];
62
+ for (let i = 2; i < process.argv.length; i += 1) {
63
+ let arg = process.argv[i];
64
+ if (!arg)
65
+ continue;
66
+ if (arg === `--help` || arg === `-h`)
67
+ printHelp();
68
+ if (arg === `--dependencies` || arg === `-d`) {
69
+ if (i + 1 >= process.argv.length)
70
+ throw new Error(`--dependencies requires a list of package names`);
71
+ i += 1;
72
+ let next = process.argv[i];
73
+ if (!next)
74
+ throw new Error(`--dependencies requires a list of package names`);
75
+ dependencies = dependencies.concat(parseDependencyList(next));
76
+ }
77
+ else if (arg.startsWith(`--dependencies=`) || arg.startsWith(`-d=`)) {
78
+ let prefix = arg.startsWith(`--dependencies=`) ? `--dependencies=` : `-d=`;
79
+ dependencies = dependencies.concat(parseDependencyList(arg.slice(prefix.length)));
80
+ }
81
+ }
82
+ return { dependencies };
83
+ }
84
+ function parseDependencyList(value) {
85
+ return value
86
+ .split(`,`)
87
+ .map((item) => item.trim())
88
+ .filter((item) => item.length > 0);
89
+ }
90
+ function parseVersionTuple(version) {
91
+ let parts = version.split(`.`);
92
+ return [
93
+ Number(parts[0]),
94
+ Number(parts[1]),
95
+ Number(parts[2]),
96
+ ];
97
+ }
98
+ function readNodeRange(packageJsonPath) {
99
+ let packageJson;
100
+ try {
101
+ packageJson = JSON.parse(readFileSync(packageJsonPath, `utf8`));
102
+ }
103
+ catch {
104
+ // Dependency package.json missing or unreadable — skip it.
105
+ return undefined;
106
+ }
107
+ let range = packageJson.engines?.node;
108
+ if (!range)
109
+ return undefined;
110
+ return range.split(`||`).map((part) => {
111
+ let version = part.match(/(\d+)(?:\.(\d+))?(?:\.(\d+))?/u);
112
+ if (!version)
113
+ throw new Error(`Cannot resolve minimum Node.js version: ${part}`);
114
+ return `${version[1]}.${version[2] ?? 0}.${version[3] ?? 0}`;
115
+ });
116
+ }
117
+ let { dependencies } = parseArgs();
118
+ let projectPackageJsonPath = resolvePackageJsonPath();
119
+ let projectRoot = path.dirname(projectPackageJsonPath);
120
+ let versions = [];
121
+ // Always include versions from the calling project itself.
122
+ let projectVersions = readNodeRange(projectPackageJsonPath);
123
+ if (projectVersions)
124
+ versions = versions.concat(projectVersions);
125
+ // Include versions from each specified dependency.
126
+ for (let dependency of dependencies) {
127
+ let dependencyVersions = readNodeRange(path.resolve(projectRoot, `node_modules`, dependency, `package.json`));
128
+ if (dependencyVersions)
129
+ versions = versions.concat(dependencyVersions);
130
+ }
131
+ let uniqueVersions = [...new Set(versions)];
132
+ // Keep only the lowest version in each major line (e.g. 22.18.0 over 22.22.2).
133
+ let byMajor = new Map();
134
+ for (let version of uniqueVersions) {
135
+ let [major, minor, patch] = parseVersionTuple(version);
136
+ let current = byMajor.get(major);
137
+ if (!current
138
+ || minor < current.tuple[1]
139
+ || (minor === current.tuple[1] && patch < current.tuple[2]))
140
+ byMajor.set(major, { version, tuple: [major, minor, patch] });
141
+ }
142
+ let outputVersions = [...byMajor.values()]
143
+ .toSorted((a, b) => {
144
+ if (a.tuple[0] !== b.tuple[0])
145
+ return a.tuple[0] - b.tuple[0];
146
+ if (a.tuple[1] !== b.tuple[1])
147
+ return a.tuple[1] - b.tuple[1];
148
+ return a.tuple[2] - b.tuple[2];
149
+ })
150
+ .map((entry) => entry.version);
151
+ if (outputVersions.length === 0)
152
+ throw new Error(`No engines.node found in the project package.json or any of the specified dependencies`);
153
+ let output = JSON.stringify(outputVersions);
154
+ if (process.env.GITHUB_OUTPUT)
155
+ appendFileSync(process.env.GITHUB_OUTPUT, `node_versions=${output}\n`);
156
+ console.info(`Node.js matrix: ${output}`);
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Get the path to the project root when deploying to GitHub Pages.
3
+ * Your action should set `REPO_NAME` and `PR_NUMBER` environment variables at the step you need
4
+ * (most likely when building the project).
5
+ * @returns {string} The path to the project directory from the domain root if working in a GitHub CI environment. If not, returns `/`.
6
+ */
7
+ export declare function getProjectRoot(): string;
@@ -0,0 +1,14 @@
1
+ import { env } from "node:process";
2
+ /**
3
+ * Get the path to the project root when deploying to GitHub Pages.
4
+ * Your action should set `REPO_NAME` and `PR_NUMBER` environment variables at the step you need
5
+ * (most likely when building the project).
6
+ * @returns {string} The path to the project directory from the domain root if working in a GitHub CI environment. If not, returns `/`.
7
+ */
8
+ export function getProjectRoot() {
9
+ if (!env.CI || !env.REPO_NAME)
10
+ return ``;
11
+ if (!env.PR_NUMBER)
12
+ return `/${env.REPO_NAME}`;
13
+ return `/${env.REPO_NAME}/${env.PR_NUMBER}`;
14
+ }
package/dist/index.d.ts CHANGED
@@ -1,21 +1,2 @@
1
- //#region src/getProjectRoot.d.ts
2
- /**
3
- * Get the path to the project root when deploying to GitHub Pages.
4
- * Your action should set `REPO_NAME` and `PR_NUMBER` environment variables at the step you need
5
- * (most likely when building the project).
6
- * @returns {string} The path to the project directory from the domain root if working in a GitHub CI environment. If not, returns `/`.
7
- */
8
- declare function getProjectRoot(): string;
9
- //#endregion
10
- //#region src/setGitHubEnvVar.d.ts
11
- /**
12
- * Sets an environment variable in the GitHub Actions environment file.
13
- * @async
14
- * @param {string} varName - The name of the environment variable to set.
15
- * @param {string} varValue - The value of the environment variable to set.
16
- * @returns {Promise<void>} A promise that resolves when the environment variable has been set.
17
- * @throws {Error} If the function is called outside of a GitHub Actions environment or if the GITHUB_ENV environment variable is not set.
18
- */
19
- declare function setGitHubEnvVar(varName: string, varValue: string): Promise<void>;
20
- //#endregion
21
- export { getProjectRoot, setGitHubEnvVar };
1
+ export { getProjectRoot } from "./get-project-root.ts";
2
+ export { setGitHubEnvVar } from "./set-github-env-var.ts";
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- import{env as e}from"node:process";import{appendFile as t}from"node:fs/promises";function n(){return!e.CI||!e.REPO_NAME?``:e.PR_NUMBER?`/${e.REPO_NAME}/${e.PR_NUMBER}`:`/${e.REPO_NAME}`}async function r(n,r){if(e.CI){if(!e.GITHUB_ENV)throw Error(`GITHUB_ENV environment variable is not set. This function should only be used in a GitHub Actions environment.`);await t(e.GITHUB_ENV,`\n${n}=${r}`)}}export{n as getProjectRoot,r as setGitHubEnvVar};
1
+ export { getProjectRoot } from "./get-project-root.js";
2
+ export { setGitHubEnvVar } from "./set-github-env-var.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Sets an environment variable in the GitHub Actions environment file.
3
+ * @async
4
+ * @param {string} varName - The name of the environment variable to set.
5
+ * @param {string} varValue - The value of the environment variable to set.
6
+ * @returns {Promise<void>} A promise that resolves when the environment variable has been set.
7
+ * @throws {Error} If the function is called outside of a GitHub Actions environment or if the GITHUB_ENV environment variable is not set.
8
+ */
9
+ export declare function setGitHubEnvVar(varName: string, varValue: string): Promise<void>;
@@ -0,0 +1,17 @@
1
+ import { appendFile } from "node:fs/promises";
2
+ import { env } from "node:process";
3
+ /**
4
+ * Sets an environment variable in the GitHub Actions environment file.
5
+ * @async
6
+ * @param {string} varName - The name of the environment variable to set.
7
+ * @param {string} varValue - The value of the environment variable to set.
8
+ * @returns {Promise<void>} A promise that resolves when the environment variable has been set.
9
+ * @throws {Error} If the function is called outside of a GitHub Actions environment or if the GITHUB_ENV environment variable is not set.
10
+ */
11
+ export async function setGitHubEnvVar(varName, varValue) {
12
+ if (!env.CI)
13
+ return;
14
+ if (!env.GITHUB_ENV)
15
+ throw new Error(`GITHUB_ENV environment variable is not set. This function should only be used in a GitHub Actions environment.`);
16
+ await appendFile(env.GITHUB_ENV, `\n${varName}=${varValue}`);
17
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@firefoxic/utils",
3
3
  "description": "Collection of useful utilities for JavaScript and Node.js.",
4
- "version": "2.1.2",
4
+ "version": "2.3.0",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "Sergey Artemov",
@@ -16,37 +16,42 @@
16
16
  "url": "git+https://github.com/firefoxic/utils.git"
17
17
  },
18
18
  "type": "module",
19
+ "types": "./dist/index.d.ts",
19
20
  "exports": {
20
21
  ".": {
21
- "import": "./dist/index.js",
22
- "types": "./dist/index.d.ts"
23
- }
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "bin": {
28
+ "get-node-matrix": "./dist/get-node-matrix.js"
24
29
  },
25
30
  "files": [
26
31
  "./dist/"
27
32
  ],
28
33
  "engines": {
29
- "node": ">=22.18"
34
+ "node": "^22.18 || ^24.15 || >=26.13"
30
35
  },
31
36
  "devEngines": {
32
37
  "runtime": {
33
38
  "name": "node",
34
- "version": ">=26.4",
39
+ "version": ">=26.13",
35
40
  "onFail": "download"
36
41
  },
37
42
  "packageManager": {
38
43
  "name": "pnpm",
39
- "version": ">=11.9",
44
+ "version": ">=12.22",
40
45
  "onFail": "download"
41
46
  }
42
47
  },
43
48
  "devDependencies": {
44
- "@firefoxic/oxlint-config": "^0.4.0",
45
- "@types/node": "^26.1.0",
46
- "oxlint": "^1.72.0",
47
- "tsdown": "^0.22.3",
48
- "typescript": "^7.0.1-rc",
49
- "node": "runtime:>=26.4"
49
+ "@firefoxic/oxlint-config": "~0.7",
50
+ "@types/node": "^26",
51
+ "@vitest/coverage-v8": "^5",
52
+ "oxlint": "^1",
53
+ "tsrs": "latest",
54
+ "vitest": "^5"
50
55
  },
51
56
  "keywords": [
52
57
  "javascript",