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// VMs read as cloud regardless of chassis. Match Hyper-V's product, since Surface shares its vendor.
40const VIRTUALIZATION_MARKERS = [
41 "qemu",
42 "kvm",
43 "bochs",
44 "vmware",
45 "virtualbox",
46 "innotek",
47 "xen",
48 "parallels",
49 "amazon ec2",
50 "google compute engine",
51 "digitalocean",
52 "hetzner",
53 "linode",
54 "vultr",
55 "scaleway",
56 "openstack",
57 "cloud",
58 "virtual machine",
59];
60
61function normalize(value: string | null | undefined): string | null {
62 const trimmed = value?.trim();
63 return trimmed && trimmed.length > 0 ? trimmed : null;
64}
65
66function machineKindFromAppleProductName(name: string): EnvironmentMachineKind | null {
67 const normalized = name.trim().toLowerCase().replaceAll(/\s+/g, "");
68 if (normalized.startsWith("macmini")) return "mac-mini";
69 if (normalized.startsWith("macstudio")) return "mac-studio";
70 if (normalized.startsWith("macbook")) return "laptop";
71 if (normalized.startsWith("imac") || normalized.startsWith("macpro")) return "desktop";
72 return null;
73}
74
75function machineKindFromDmi(input: {
76 readonly chassisType: string | null;
77 readonly sysVendor: string | null;
78 readonly productName: string | null;
79}): EnvironmentMachineKind | null {
80 const productName = input.productName ?? "";
81 const vendorAndProduct = `${input.sysVendor ?? ""} ${productName}`.toLowerCase();
82 if (VIRTUALIZATION_MARKERS.some((marker) => vendorAndProduct.includes(marker))) {
83 return "cloud";
84 }
85 const appleKind = machineKindFromAppleProductName(productName);
86 if (appleKind !== null) {
87 return appleKind;
88 }
89 return input.chassisType === null ? null : (DMI_CHASSIS_KINDS[input.chassisType] ?? null);
90}
91
92const readOptionalFile = Effect.fn("readOptionalFile")(function* (path: string) {
93 const fileSystem = yield* FileSystem.FileSystem;
94 return yield* fileSystem.readFileString(path).pipe(
95 Effect.map(normalize),
96 Effect.orElseSucceed(() => null),
97 );
98});
99
100const runProbe = Effect.fn("runMachineProbe")(function* (input: {
101 readonly command: string;
102 readonly args: ReadonlyArray<string>;
103}) {
104 const processRunner = yield* ProcessRunner.ProcessRunner;
105 return yield* processRunner
106 .run({
107 command: input.command,
108 args: input.args,
109 timeout: "5 seconds",
110 timeoutBehavior: "timedOutResult",
111 })
112 .pipe(
113 Effect.map((result) => (result.code === 0 ? normalize(result.stdout) : null)),
114 Effect.orElseSucceed(() => null),
115 );
116});
117
118// Apple silicon exposes IOKit's marketing name; Intel needs the hw.model fallback.
119const detectDarwinMachineKind = Effect.fn("detectDarwinMachineKind")(function* () {
120 const ioreg = yield* runProbe({ command: "ioreg", args: ["-rd1", "-n", "product"] });
121 const productName = ioreg?.match(/"product-name"\s*=\s*<"([^"]+)">/)?.[1] ?? null;
122 const fromProductName =
123 productName === null ? null : machineKindFromAppleProductName(productName);
124 if (fromProductName !== null) {
125 return fromProductName;
126 }
127 const model = yield* runProbe({ command: "sysctl", args: ["-n", "hw.model"] });
128 return model === null ? null : machineKindFromAppleProductName(model);
129});
130
131const detectLinuxMachineKind = Effect.fn("detectLinuxMachineKind")(function* () {
132 const [kernelRelease, chassisType, sysVendor, productName] = yield* Effect.all([
133 readOptionalFile(KERNEL_RELEASE_PATH),
134 readOptionalFile(`${DMI_ROOT}/chassis_type`),
135 readOptionalFile(`${DMI_ROOT}/sys_vendor`),
136 readOptionalFile(`${DMI_ROOT}/product_name`),
137 ]);
138 // Check WSL first; WSL 2 presents as a Hyper-V VM in DMI.
139 if (kernelRelease?.toLowerCase().includes("microsoft")) {
140 return "linux";
141 }
142 return machineKindFromDmi({ chassisType, sysVendor, productName });
143});
144
145export const detectServerEnvironmentMachineKind = Effect.fn("detectServerEnvironmentMachineKind")(
146 function* () {
147 const platform = yield* HostProcess.Platform;
148 switch (platform) {
149 case "darwin":
150 return yield* detectDarwinMachineKind();
151 case "linux":
152 return yield* detectLinuxMachineKind();
153 default:
154 return null;
155 }
156 },
157);