From 6a6c1f9e9d7aef0e5e6a8662ff209795a0baf7e6 Mon Sep 17 00:00:00 2001 From: Jake Jarvis Date: Wed, 10 Mar 2021 14:47:17 -0500 Subject: [PATCH] Detect ARM64 macOS running on Apple Silicon Also distinguishes whether 64-bit Node is running because we're actually on an Intel Mac or if it's just Rosetta 2 pretending to be one. --- index.d.ts | 3 +-- index.js | 9 +++++++-- test/basic.js | 4 ++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/index.d.ts b/index.d.ts index acbce66..a2e2c1e 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,4 +1,3 @@ - -declare function arch(): 'x64' | 'x86'; +declare function arch(): 'x64' | 'x86' | 'arm64'; export = arch; diff --git a/index.js b/index.js index 7d90b8a..956b622 100644 --- a/index.js +++ b/index.js @@ -17,10 +17,15 @@ module.exports = function arch () { } /** - * All recent versions of Mac OS are 64-bit. + * On macOS, we need to detect if x64 Node is running because the CPU is truly + * an Intel chip, or if it's running on Apple Silicon via Rosetta 2: + * https://developer.apple.com/documentation/apple-silicon/about-the-rosetta-translation-environment */ if (process.platform === 'darwin') { - return 'x64' + var nativeArm = process.arch === 'arm64' + var rosettaArm = cp.execSync('sysctl -in sysctl.proc_translated', { encoding: 'utf8' }) === '1\n' + + return (nativeArm || rosettaArm) ? 'arm64' : 'x64' } /** diff --git a/test/basic.js b/test/basic.js index 8d6de32..64177e4 100644 --- a/test/basic.js +++ b/test/basic.js @@ -1,8 +1,8 @@ var arch = require('../') var test = require('tape') -test('returns x86 or x64', function (t) { +test('returns a valid architecture', function (t) { var str = arch() - t.ok(str === 'x86' || str === 'x64') + t.ok(str === 'x86' || str === 'x64' || str === 'arm64') t.end() })