Open History to see the last commit
1import type { EnvironmentMachineKind } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5
6import * as ProcessRunner from "../processRunner.ts";
7
8const DMI_ROOT = "/sys/class/dmi/id";
9const KERNEL_RELEASE_PATH = "/proc/sys/kernel/osrelease";
10
11// SMBIOS 3.x System Enclosure types (table 17).
12const DMI_CHASSIS_KINDS: Readonly<Record<string, EnvironmentMachineKind>> = {
13 "3": "desktop",
14 "4": "desktop",
15 "5": "desktop",
16 "6": "desktop",
17 "7": "desktop",
18 "8": "laptop",
19 "9": "laptop",
20 "10": "laptop",
21 "13": "desktop",
22 "14": "laptop",
23 "15": "desktop",
24 "16": "desktop",
25 "17": "server",
26 "18": "server",
27 "19": "server",
28 "20": "server",
29 "21": "server",
30 "22": "server",
31 "23": "server",
32 "24": "server",
33 "28": "server",
34 "31": "laptop",
35 "32": "laptop",
36 "35": "desktop",
37};
38
39// Hypervisors and cloud providers write themselves into the DMI vendor or
40// product strings; any hit means the box is a VM, and a VM reads as "cloud"
41// regardless of the chassis type the hypervisor fakes. Hyper-V is matched on
42// its "Virtual Machine" product, not the "Microsoft Corporation" vendor that
43// physical Surface devices share.
44const VIRTUALIZATION_MARKERS = [
45 "qemu",
46 "kvm",
47 "bochs",
48 "vmware",
49 "virtualbox",
50 "innotek",
51 "xen",
52 "parallels",
53 "amazon ec2",
54 "google compute engine",
55 "digitalocean",
56 "hetzner",
57 "linode",
58 "vultr",
59 "scaleway",
60 "openstack",
61 "cloud",
62 "virtual machine",
63];
64
65function normalize(value: string | null | undefined): string | null {
66 const trimmed = value?.trim();
67 return trimmed && trimmed.length > 0 ? trimmed : null;
68}
69
70export function machineKindFromAppleProductName(name: string): EnvironmentMachineKind | null {
71 const normalized = name.trim().toLowerCase().replaceAll(/\s+/g, "");
72 if (normalized.startsWith("macmini")) return "mac-mini";
73 if (normalized.startsWith("macstudio")) return "mac-studio";
74 if (normalized.startsWith("macbook")) return "laptop";
75 if (normalized.startsWith("imac") || normalized.startsWith("macpro")) return "desktop";
76 return null;
77}
78
79export function machineKindFromDmi(input: {
80 readonly chassisType: string | null;
81 readonly sysVendor: string | null;
82 readonly productName: string | null;
83}): EnvironmentMachineKind | null {
84 const productName = input.productName ?? "";
85 const vendorAndProduct = `${input.sysVendor ?? ""} ${productName}`.toLowerCase();
86 if (VIRTUALIZATION_MARKERS.some((marker) => vendorAndProduct.includes(marker))) {
87 return "cloud";
88 }
89 const appleKind = machineKindFromAppleProductName(productName);
90 if (appleKind !== null) {
91 return appleKind;
92 }
93 return input.chassisType === null ? null : (DMI_CHASSIS_KINDS[input.chassisType] ?? null);
94}
95
96const readOptionalFile = Effect.fn("readOptionalFile")(function* (path: string) {
97 const fileSystem = yield* FileSystem.FileSystem;
98 return yield* fileSystem.readFileString(path).pipe(
99 Effect.map(normalize),
100 Effect.orElseSucceed(() => null),
101 );
102});
103
104const runProbe = Effect.fn("runMachineProbe")(function* (input: {
105 readonly command: string;
106 readonly args: ReadonlyArray<string>;
107}) {
108 const processRunner = yield* ProcessRunner.ProcessRunner;
109 return yield* processRunner
110 .run({
111 command: input.command,
112 args: input.args,
113 timeout: "5 seconds",
114 timeoutBehavior: "timedOutResult",
115 })
116 .pipe(
117 Effect.map((result) => (result.code === 0 ? normalize(result.stdout) : null)),
118 Effect.orElseSucceed(() => null),
119 );
120});
121
122// IOKit's `product` node carries the marketing name ("Mac mini (2024)") on
123// Apple silicon; Intel Macs lack it, so `hw.model` ("Macmini8,1") is the
124// fallback.
125const detectDarwinMachineKind = Effect.fn("detectDarwinMachineKind")(function* () {
126 const ioreg = yield* runProbe({ command: "ioreg", args: ["-rd1", "-n", "product"] });
127 const productName = ioreg?.match(/"product-name"\s*=\s*<"([^"]+)">/)?.[1] ?? null;
128 const fromProductName =
129 productName === null ? null : machineKindFromAppleProductName(productName);
130 if (fromProductName !== null) {
131 return fromProductName;
132 }
133 const model = yield* runProbe({ command: "sysctl", args: ["-n", "hw.model"] });
134 return model === null ? null : machineKindFromAppleProductName(model);
135});
136
137const detectLinuxMachineKind = Effect.fn("detectLinuxMachineKind")(function* () {
138 const [kernelRelease, chassisType, sysVendor, productName] = yield* Effect.all([
139 readOptionalFile(KERNEL_RELEASE_PATH),
140 readOptionalFile(`${DMI_ROOT}/chassis_type`),
141 readOptionalFile(`${DMI_ROOT}/sys_vendor`),
142 readOptionalFile(`${DMI_ROOT}/product_name`),
143 ]);
144 // WSL exposes Microsoft in its kernel release on both WSL 1 and WSL 2.
145 // Check it before DMI because WSL 2 presents as a Hyper-V VM.
146 if (kernelRelease?.toLowerCase().includes("microsoft")) {
147 return "linux";
148 }
149 return machineKindFromDmi({ chassisType, sysVendor, productName });
150});
151
152export const detectServerEnvironmentMachineKind = Effect.fn("detectServerEnvironmentMachineKind")(
153 function* () {
154 const platform = yield* HostProcess.Platform;
155 switch (platform) {
156 case "darwin":
157 return yield* detectDarwinMachineKind();
158 case "linux":
159 return yield* detectLinuxMachineKind();
160 default:
161 return null;
162 }
163 },
164);