goatly 0.1.0 → 0.1.2

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.
Files changed (161) hide show
  1. package/README.md +874 -1
  2. package/bin/goatly.js +99 -0
  3. package/dist/cli/index.js +234 -0
  4. package/dist/compat/gatsby-node-entry.js +16 -0
  5. package/dist/compat/gatsby-package.json +6 -0
  6. package/dist/compat/md5-file.js +47 -0
  7. package/dist/compat-apis.json +72 -0
  8. package/dist/compat-apis.json.js +62 -0
  9. package/dist/graphql.js +3 -0
  10. package/dist/node/actions/index.js +619 -0
  11. package/dist/node/actions/job-store.js +180 -0
  12. package/dist/node/actions/jobs.js +174 -0
  13. package/dist/node/api-runner.js +258 -0
  14. package/dist/node/bootstrap.js +569 -0
  15. package/dist/node/build/assets.js +110 -0
  16. package/dist/node/build/incremental.js +208 -0
  17. package/dist/node/build/index.js +763 -0
  18. package/dist/node/build/memory-governor.js +450 -0
  19. package/dist/node/build/output-dirs.js +70 -0
  20. package/dist/node/build/page-data.js +40 -0
  21. package/dist/node/build/page-files.js +186 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +626 -0
  24. package/dist/node/build/query-workers.js +863 -0
  25. package/dist/node/build/render-thread.js +103 -0
  26. package/dist/node/build/render-worker.js +162 -0
  27. package/dist/node/build/state.js +24 -0
  28. package/dist/node/build/timing-breakdown.js +216 -0
  29. package/dist/node/build/work-clock.js +75 -0
  30. package/dist/node/build/worker-pool.js +242 -0
  31. package/dist/node/cache-layout.js +99 -0
  32. package/dist/node/cache.js +1430 -0
  33. package/dist/node/compat/chokidar-shim.js +148 -0
  34. package/dist/node/compat/core-utils-lmdb.js +145 -0
  35. package/dist/node/compat/create-node-id-shim.js +1 -0
  36. package/dist/node/compat/module-hooks.js +245 -0
  37. package/dist/node/compat/redux-shim.js +1 -0
  38. package/dist/node/config/index.js +162 -0
  39. package/dist/node/config/not-found-pages.js +95 -0
  40. package/dist/node/datastore/codec.js +144 -0
  41. package/dist/node/datastore/index.js +127 -0
  42. package/dist/node/datastore/logfile/cache.js +89 -0
  43. package/dist/node/datastore/logfile/index.js +1329 -0
  44. package/dist/node/datastore/logfile/record.js +71 -0
  45. package/dist/node/datastore/types.js +1 -0
  46. package/dist/node/develop/express-compat.js +207 -0
  47. package/dist/node/develop/graphiql.js +22 -0
  48. package/dist/node/develop/hydration-report.js +41 -0
  49. package/dist/node/develop/index.js +618 -0
  50. package/dist/node/develop/local-url.js +10 -0
  51. package/dist/node/develop/ssr-runner.js +66 -0
  52. package/dist/node/gql.js +5 -0
  53. package/dist/node/index.js +15 -0
  54. package/dist/node/info.js +270 -0
  55. package/dist/node/internal-plugins/data-bridge.js +196 -0
  56. package/dist/node/internal-plugins/page-creator.js +318 -0
  57. package/dist/node/loader/import-module.js +160 -0
  58. package/dist/node/node-helpers.js +66 -0
  59. package/dist/node/not-found-pages.js +220 -0
  60. package/dist/node/plugins/api-list.js +12 -0
  61. package/dist/node/plugins/load-plugins.js +427 -0
  62. package/dist/node/plugins/resolve-plugin.js +79 -0
  63. package/dist/node/plugins/static-exports.js +64 -0
  64. package/dist/node/query/compile.js +326 -0
  65. package/dist/node/query/dependencies.js +45 -0
  66. package/dist/node/query/execute.js +417 -0
  67. package/dist/node/query/extract.js +372 -0
  68. package/dist/node/query/gql-tada-introspection.js +124 -0
  69. package/dist/node/query/graphql-env.js +231 -0
  70. package/dist/node/query/graphql-runner.js +79 -0
  71. package/dist/node/redux/actions.js +1 -0
  72. package/dist/node/redux/index.js +133 -0
  73. package/dist/node/redux/node-changes.js +128 -0
  74. package/dist/node/redux/reducers.js +193 -0
  75. package/dist/node/redux/state.js +71 -0
  76. package/dist/node/renderer.js +124 -0
  77. package/dist/node/reporter-transports.js +259 -0
  78. package/dist/node/reporter.js +497 -0
  79. package/dist/node/schema/date.js +539 -0
  80. package/dist/node/schema/extensions.js +315 -0
  81. package/dist/node/schema/index.js +542 -0
  82. package/dist/node/schema/infer.js +388 -0
  83. package/dist/node/schema/inline-objects.js +128 -0
  84. package/dist/node/schema/naming.js +20 -0
  85. package/dist/node/schema/node-model.js +207 -0
  86. package/dist/node/schema/query-engine.js +1808 -0
  87. package/dist/node/schema/resolver-kinds.js +7 -0
  88. package/dist/node/schema/resolvers.js +273 -0
  89. package/dist/node/schema/type-builders.js +45 -0
  90. package/dist/node/schema/types.js +241 -0
  91. package/dist/node/serve.js +90 -0
  92. package/dist/node/site-page-nodes.js +277 -0
  93. package/dist/node/types.js +1 -0
  94. package/dist/node/utils/content-digest.js +107 -0
  95. package/dist/node/utils/cpus.js +104 -0
  96. package/dist/node/utils/create-node-id.js +51 -0
  97. package/dist/node/utils/env.js +25 -0
  98. package/dist/node/utils/fs-retry.js +74 -0
  99. package/dist/node/utils/memory-signals.js +441 -0
  100. package/dist/node/utils/memory.js +657 -0
  101. package/dist/node/utils/murmurhash.js +32 -0
  102. package/dist/node/utils/parser.js +33 -0
  103. package/dist/node/utils/partition-hash.js +19 -0
  104. package/dist/node/utils/paths.js +122 -0
  105. package/dist/node/utils/resolver.js +48 -0
  106. package/dist/node/utils/runtime.js +5 -0
  107. package/dist/node/utils/serializable.js +41 -0
  108. package/dist/node/utils/strings.js +41 -0
  109. package/dist/node/vite/config.js +289 -0
  110. package/dist/node/vite/paths.js +12 -0
  111. package/dist/node/vite/plugin-deps.js +232 -0
  112. package/dist/node/vite/plugin.js +283 -0
  113. package/dist/node/vite/react-compiler.js +362 -0
  114. package/dist/node/vite/source-files.js +83 -0
  115. package/dist/node/vite/static-image.js +136 -0
  116. package/dist/node/vite/styled-components.js +73 -0
  117. package/dist/node/vite/transforms.js +330 -0
  118. package/dist/node/wasm-data/host.js +406 -0
  119. package/dist/node/wasm-data/lower.js +406 -0
  120. package/dist/node/wasm-data/runner.js +79 -0
  121. package/dist/node/wasm-data/worker.js +95 -0
  122. package/dist/reporter.js +5 -0
  123. package/dist/runtime/api-runner.js +81 -0
  124. package/dist/runtime/app.js +256 -0
  125. package/dist/runtime/client-entry.js +4 -0
  126. package/dist/runtime/client.js +383 -0
  127. package/dist/runtime/default-html.js +31 -0
  128. package/dist/runtime/head-markup.js +100 -0
  129. package/dist/runtime/head-sync.js +101 -0
  130. package/dist/runtime/head-tags.js +45 -0
  131. package/dist/runtime/hydration-report.js +111 -0
  132. package/dist/runtime/index.js +12 -0
  133. package/dist/runtime/link.js +293 -0
  134. package/dist/runtime/loader.js +449 -0
  135. package/dist/runtime/not-found.js +61 -0
  136. package/dist/runtime/page-renderer.js +35 -0
  137. package/dist/runtime/preamble.js +47 -0
  138. package/dist/runtime/react-compat.js +14 -0
  139. package/dist/runtime/renderer-shared.js +10 -0
  140. package/dist/runtime/renderers/react-client.js +14 -0
  141. package/dist/runtime/renderers/react-server.js +99 -0
  142. package/dist/runtime/renderers/react.js +17 -0
  143. package/dist/runtime/renderers/types.js +1 -0
  144. package/dist/runtime/root-error-handlers.js +29 -0
  145. package/dist/runtime/router/history.js +132 -0
  146. package/dist/runtime/router/index.js +240 -0
  147. package/dist/runtime/router/utils.js +118 -0
  148. package/dist/runtime/script.js +110 -0
  149. package/dist/runtime/scroll.js +40 -0
  150. package/dist/runtime/slice.js +11 -0
  151. package/dist/runtime/ssr.js +240 -0
  152. package/dist/runtime/static-query.js +47 -0
  153. package/dist/utils.js +4 -0
  154. package/package.json +105 -3
  155. package/types/graphql-tada.d.ts +223 -0
  156. package/types/graphql.d.ts +2 -0
  157. package/types/index.d.ts +2287 -0
  158. package/types/node.d.ts +389 -0
  159. package/types/reporter.d.ts +187 -0
  160. package/types/router.d.ts +102 -0
  161. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,441 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import { execFile, execFileSync } from "node:child_process";
5
+ // src/node/utils/memory-signals.ts
6
+ /**
7
+ * Measured memory signals: how much memory this build process may still use, sampled often (an
8
+ * adaptive worker pool samples every 250 ms – a Linux sample reads a few small /proc and cgroup
9
+ * files, tens of µs). Correct in containers: on Linux the headroom of every cgroup level counts, its
10
+ * page cache as free. (Not process.availableMemory(): on Node it counts the page cache as used
11
+ * – it fell by 1 GB after a 1 GB file was written – and on Bun it ignores cgroups.)
12
+ */
13
+ const MB = 1048576;
14
+ /** cgroup limits from here on mean "none" (cgroup v1 reports 2^63 − a page) */
15
+ const UNLIMITED = 2 ** 60;
16
+ const VM_STAT = "/usr/bin/vm_stat";
17
+ const SYSCTL = "/usr/sbin/sysctl";
18
+ /** how often macOS's `vm_stat` runs in the background (ms; one run takes ~10 ms) */
19
+ const VM_STAT_INTERVAL_MS = 1e3;
20
+ /**
21
+ * Memory (MB) that is available on macOS, like Activity Monitor computes it:
22
+ * total − (app memory + wired + compressed), from `vm_stat` output. Unlike os.freemem() (only
23
+ * completely free pages – often ~100 MB on a busy Mac) this counts reclaimable file cache and
24
+ * inactive memory as available. undefined when the output can't be parsed.
25
+ */
26
+ function parseVmStatAvailableMb(vmStat, totalBytes) {
27
+ const pageSize = Number(/page size of (\d+) bytes/.exec(vmStat)?.[1]);
28
+ const pages = (label) => {
29
+ const match = new RegExp(`^${label}:\\s+(\\d+)\\.`, "m").exec(vmStat);
30
+ return match ? Number(match[1]) : NaN;
31
+ };
32
+ const usedPages = pages("Anonymous pages") - pages("Pages purgeable") + pages("Pages wired down") + pages("Pages occupied by compressor");
33
+ if (!(pageSize > 0) || Number.isNaN(usedPages)) return void 0;
34
+ return Math.max(0, (totalBytes - usedPages * pageSize) / MB);
35
+ }
36
+ /**
37
+ * macOS's memory pressure level – what Activity Monitor's "Memory Pressure" shows – from
38
+ * `sysctl -n kern.memorystatus_vm_pressure_level` (1 normal, 2 warn, 4 critical), undefined when
39
+ * the output is something else
40
+ */
41
+ function parsePressureLevel(text) {
42
+ const value = text.trim();
43
+ return value === "1" ? "normal" : value === "2" ? "warn" : value === "4" ? "critical" : void 0;
44
+ }
45
+ /** MemTotal and MemAvailable (free + reclaimable, the kernel's estimate) of /proc/meminfo, in MB */
46
+ function parseMeminfo(text) {
47
+ const total = /^MemTotal:\s+(\d+) kB/m.exec(text);
48
+ const available = /^MemAvailable:\s+(\d+) kB/m.exec(text);
49
+ if (!total || !available) return void 0;
50
+ return {
51
+ totalMb: Number(total[1]) / 1024,
52
+ availableMb: Number(available[1]) / 1024
53
+ };
54
+ }
55
+ /** RssAnon of /proc/<pid>/status (MB): the process's anonymous resident memory */
56
+ function parseStatusRssAnonMb(text) {
57
+ const match = /^RssAnon:\s+(\d+) kB/m.exec(text);
58
+ return match ? Number(match[1]) / 1024 : void 0;
59
+ }
60
+ /** a cgroup limit (bytes) – memory.max, memory.high, memory.limit_in_bytes: Infinity for none, NaN for garbage */
61
+ function parseCgroupLimit(text) {
62
+ const value = text.trim();
63
+ if (value === "max") return 1e400;
64
+ const bytes = value === "" ? NaN : Number(value);
65
+ return bytes >= UNLIMITED || bytes < 0 ? 1e400 : bytes;
66
+ }
67
+ /** a pattern per memory.stat key (~1 µs for a file's keys – splitting it into lines costs 5) */
68
+ const statKeys = /* @__PURE__ */ new Map();
69
+ /** the value of the first of `keys` in memory.stat, else 0 */
70
+ function statValue(text, ...keys) {
71
+ for (const key of keys) {
72
+ let pattern = statKeys.get(key);
73
+ if (!pattern) statKeys.set(key, pattern = new RegExp(`^${key} (\\d+)$`, "m"));
74
+ const match = pattern.exec(text);
75
+ if (match) return Number(match[1]);
76
+ }
77
+ return 0;
78
+ }
79
+ /**
80
+ * The page cache counters (bytes) of a cgroup's memory.stat – hierarchical (descendants included):
81
+ * v1's total_* keys (the plain keys without them), v2's keys are. `hierarchicalLimit` (v1): the
82
+ * lowest limit of the cgroup and its ancestors (Infinity for none).
83
+ */
84
+ function parseCgroupStat(text, version) {
85
+ const value = (...keys) => statValue(text, ...keys);
86
+ if (version === "v2") return {
87
+ activeFile: value("active_file"),
88
+ inactiveFile: value("inactive_file"),
89
+ dirty: value("file_dirty"),
90
+ writeback: value("file_writeback")
91
+ };
92
+ const hierarchical = /^hierarchical_memory_limit (\d+)$/m.exec(text)?.[1];
93
+ return {
94
+ activeFile: value("total_active_file", "active_file"),
95
+ inactiveFile: value("total_inactive_file", "inactive_file"),
96
+ dirty: value("total_dirty", "dirty"),
97
+ writeback: value("total_writeback", "writeback"),
98
+ ...hierarchical !== void 0 ? { hierarchicalLimit: parseCgroupLimit(hierarchical) } : {}
99
+ };
100
+ }
101
+ /** the "some" line's total= (µs) of a PSI file (/proc/pressure/memory, memory.pressure) */
102
+ function parsePsiSomeTotal(text) {
103
+ const match = /^some .*\btotal=(\d+)/m.exec(text);
104
+ return match ? Number(match[1]) : void 0;
105
+ }
106
+ /**
107
+ * GOATLY_TEST_MEMORY (for tests), e.g. "0:16000,200:3000,400:16000": the memory capacity (MB)
108
+ * from a number of queried pages on, sorted by pages (a bare "8000": from 0 on). Invalid entries are
109
+ * left out.
110
+ */
111
+ function parseTestMemory(spec) {
112
+ const steps = [];
113
+ for (const entry of spec.split(",")) {
114
+ const parts = entry.split(":").map((part) => part.trim());
115
+ if (parts.length > 2 || parts.some((part) => part === "")) continue;
116
+ const [queried, capacityMb] = parts.length === 2 ? parts.map(Number) : [0, Number(parts[0])];
117
+ if (queried >= 0 && capacityMb >= 0) steps.push([queried, capacityMb]);
118
+ }
119
+ return steps.sort((a, b) => a[0] - b[0]);
120
+ }
121
+ /**
122
+ * The capacity of the step with the largest key <= `queried` (before the first key: the first
123
+ * capacity; Infinity without steps)
124
+ */
125
+ function capacityAt(steps, queried) {
126
+ let step;
127
+ for (const s of steps) if (s[0] <= queried && (!step || s[0] >= step[0])) step = s;
128
+ if (!step) {
129
+ for (const s of steps) if (!step || s[0] < step[0]) step = s;
130
+ }
131
+ return step ? step[1] : 1e400;
132
+ }
133
+ /**
134
+ * The cgroup levels of a controller (e.g. "memory", "cpu") that apply to this process, from
135
+ * /proc/self/cgroup: its own cgroup – or, when that isn't visible here (e.g. in a container that
136
+ * sees only its part of the hierarchy), the nearest ancestor that is, else the mount – then each
137
+ * ancestor, up to the mount. Only levels that have all of `files` (by cgroup version) are returned:
138
+ * the root of cgroup v2 has no limits. cgroup v1's controller wins over a v2 hierarchy (hybrid
139
+ * setups mount both).
140
+ */
141
+ function findCgroupLevels(procSelfCgroup, controller, files, root = "/sys/fs/cgroup") {
142
+ let v1;
143
+ /** the controllers mounted with it, as the mount is named (e.g. "cpu,cpuacct") */
144
+ let mounted = controller;
145
+ let v2;
146
+ for (const line of procSelfCgroup.split("\n")) {
147
+ const match = /^(\d+):([^:]*):(.*)$/.exec(line.trim());
148
+ if (!match) continue;
149
+ if (match[1] === "0" && match[2] === "") v2 = match[3];
150
+ else if (match[2].split(",").includes(controller)) {
151
+ v1 = match[3];
152
+ mounted = match[2];
153
+ }
154
+ }
155
+ const version = v1 !== void 0 ? "v1" : "v2";
156
+ const own = v1 ?? v2;
157
+ if (own === void 0) return [];
158
+ const mount = version === "v2" ? root : v1Mount(root, controller, mounted);
159
+ const levels = [];
160
+ for (let rel = path.posix.join("/", own);; rel = path.posix.dirname(rel)) {
161
+ const dir = rel === "/" ? mount : path.join(mount, rel);
162
+ if (files[version].every((file) => fs.existsSync(path.join(dir, file)))) levels.push({
163
+ version,
164
+ dir
165
+ });
166
+ if (rel === "/") return levels;
167
+ }
168
+ }
169
+ /**
170
+ * Where a cgroup v1 controller is mounted below `root`: under its own name (often a link to the
171
+ * mount it shares), under the names it is mounted with as /proc/self/cgroup lists them – or in the
172
+ * other order ("cpuacct,cpu" for the mount "cpu,cpuacct").
173
+ */
174
+ function v1Mount(root, controller, mounted) {
175
+ for (const name of [controller, mounted]) {
176
+ const dir = path.join(root, name);
177
+ if (fs.existsSync(dir)) return dir;
178
+ }
179
+ try {
180
+ const shared = fs.readdirSync(root).find((name) => name.split(",").includes(controller));
181
+ if (shared) return path.join(root, shared);
182
+ } catch {}
183
+ return path.join(root, controller);
184
+ }
185
+ /**
186
+ * The cgroup levels whose memory limits apply to this process (see findCgroupLevels): those with
187
+ * a limit and usage file.
188
+ */
189
+ function findMemoryCgroups(procSelfCgroup, root = "/sys/fs/cgroup") {
190
+ return findCgroupLevels(procSelfCgroup, "memory", {
191
+ v1: ["memory.limit_in_bytes", "memory.usage_in_bytes"],
192
+ v2: ["memory.max", "memory.current"]
193
+ }, root);
194
+ }
195
+ /** a reading of a file, undefined when it can't be read or parsed */
196
+ function readWith(file, parse) {
197
+ try {
198
+ return parse(fs.readFileSync(file, "utf8"));
199
+ } catch {
200
+ return;
201
+ }
202
+ }
203
+ const read = (file) => fs.readFileSync(file, "utf8");
204
+ /** a byte count (memory.current, memory.usage_in_bytes), NaN for garbage */
205
+ function parseBytes(text) {
206
+ const value = text.trim();
207
+ return value === "" ? NaN : Number(value);
208
+ }
209
+ /** the process's RSS (MB) – 0 when it can't be measured (Node reads /proc/self/stat on Linux) */
210
+ function rssMb() {
211
+ try {
212
+ const usage = process.memoryUsage;
213
+ return (typeof usage.rss === "function" ? usage.rss() : usage().rss) / MB;
214
+ } catch {
215
+ return 0;
216
+ }
217
+ }
218
+ /** the memory (MB) of the machine, or the container limit Node sees when that is smaller */
219
+ function totalMb() {
220
+ const total = os.totalmem();
221
+ const constrained = typeof process.constrainedMemory === "function" ? process.constrainedMemory() : 0;
222
+ return (constrained > 0 && constrained < total ? constrained : total) / MB;
223
+ }
224
+ /** the process's anonymous RSS (MB) from /proc/self/status, else its RSS */
225
+ function ownMemory(platform, procRoot) {
226
+ if (platform !== "linux") return rssMb;
227
+ const status = path.join(procRoot, "self/status");
228
+ return () => readWith(status, parseStatusRssAnonMb) ?? rssMb();
229
+ }
230
+ /** the limit and the headroom below it (bytes) of a cgroup level, undefined without a limit */
231
+ function readLevel(level) {
232
+ try {
233
+ let limit = 1e400;
234
+ for (const file of level.limits) limit = Math.min(limit, parseCgroupLimit(read(file)));
235
+ let stat;
236
+ if (level.version === "v1" && (limit < 1e400 || level.top)) {
237
+ stat = parseCgroupStat(read(level.stat), "v1");
238
+ limit = Math.min(limit, stat.hierarchicalLimit ?? 1e400);
239
+ }
240
+ if (!(limit < 1e400)) return void 0;
241
+ const usage = parseBytes(read(level.usage));
242
+ stat ??= parseCgroupStat(read(level.stat), level.version);
243
+ if (!(usage >= 0)) return void 0;
244
+ const clean = Math.max(0, stat.activeFile + stat.inactiveFile);
245
+ return {
246
+ limit,
247
+ headroom: limit - Math.max(0, usage - clean)
248
+ };
249
+ } catch {
250
+ return;
251
+ }
252
+ }
253
+ function linuxSampler(options) {
254
+ const proc = options.procRoot ?? "/proc";
255
+ const meminfo = path.join(proc, "meminfo");
256
+ const own = ownMemory("linux", proc);
257
+ const levels = findMemoryCgroups(readWith(path.join(proc, "self/cgroup"), (text) => text) ?? "", options.cgroupRoot);
258
+ const files = levels.map(({ version, dir }, i) => ({
259
+ version,
260
+ limits: version === "v2" ? [path.join(dir, "memory.max"), path.join(dir, "memory.high")] : [path.join(dir, "memory.limit_in_bytes")],
261
+ usage: path.join(dir, version === "v2" ? "memory.current" : "memory.usage_in_bytes"),
262
+ stat: path.join(dir, "memory.stat"),
263
+ top: i === levels.length - 1
264
+ }));
265
+ const psi = [...levels[0]?.version === "v2" ? [path.join(levels[0].dir, "memory.pressure")] : [], path.join(proc, "pressure/memory")].find((file) => readWith(file, parsePsiSomeTotal) !== void 0);
266
+ return {
267
+ sample() {
268
+ const t = performance.now();
269
+ const system = readWith(meminfo, parseMeminfo);
270
+ let availMb = system ? system.availableMb : os.freemem() / MB;
271
+ let limitMb = system ? system.totalMb : os.totalmem() / MB;
272
+ let source = system ? "meminfo" : "os";
273
+ for (const level of files) {
274
+ const cgroup = readLevel(level);
275
+ if (!cgroup) continue;
276
+ availMb = Math.min(availMb, cgroup.headroom / MB);
277
+ limitMb = Math.min(limitMb, cgroup.limit / MB);
278
+ source = level.version === "v2" ? "cgroup-v2" : "cgroup-v1";
279
+ }
280
+ const psiSomeUs = psi ? readWith(psi, parsePsiSomeTotal) : void 0;
281
+ return {
282
+ t,
283
+ availMb: Math.max(0, availMb),
284
+ ownMb: own(),
285
+ limitMb,
286
+ ...psiSomeUs !== void 0 ? { psiSomeUs } : {},
287
+ ageMs: 0,
288
+ source
289
+ };
290
+ },
291
+ close() {}
292
+ };
293
+ }
294
+ /**
295
+ * macOS: `vm_stat` (Activity Monitor's available memory) runs every second in the background
296
+ * (`poll`); in between, the process's own growth since is subtracted. The first sample before a
297
+ * background result runs it synchronously. After each, `sysctl` reads the memory pressure level
298
+ * (macOS compresses and swaps out idle memory before it runs out: the level, not the available
299
+ * memory, says when that slows the system down).
300
+ */
301
+ function darwinSampler(poll) {
302
+ let reading;
303
+ let pressureLevel;
304
+ let synchronous = false;
305
+ let closed = false;
306
+ let timer;
307
+ let child;
308
+ /** `ownMb` and `t`: when vm_stat ran (not when its output arrived: the build grew meanwhile) */
309
+ const record = (out, ownMb, t) => {
310
+ const availMb = parseVmStatAvailableMb(out, os.totalmem());
311
+ if (availMb !== void 0) reading = {
312
+ availMb,
313
+ ownMb,
314
+ t
315
+ };
316
+ };
317
+ const next = () => {
318
+ if (closed) return;
319
+ const ownMb = rssMb();
320
+ const t = performance.now();
321
+ child = execFile(VM_STAT, {
322
+ encoding: "utf8",
323
+ timeout: 2e3
324
+ }, (error, out) => {
325
+ child = void 0;
326
+ if (!error) record(out, ownMb, t);
327
+ if (closed) return;
328
+ child = execFile(SYSCTL, ["-n", "kern.memorystatus_vm_pressure_level"], {
329
+ encoding: "utf8",
330
+ timeout: 2e3
331
+ }, (failed, level) => {
332
+ child = void 0;
333
+ pressureLevel = failed ? void 0 : parsePressureLevel(level);
334
+ if (closed) return;
335
+ timer = setTimeout(next, VM_STAT_INTERVAL_MS);
336
+ timer.unref();
337
+ });
338
+ });
339
+ };
340
+ if (poll) next();
341
+ return {
342
+ sample() {
343
+ const t = performance.now();
344
+ if (!reading && !synchronous) {
345
+ synchronous = true;
346
+ try {
347
+ const ownMb = rssMb();
348
+ const at = performance.now();
349
+ record(execFileSync(VM_STAT, {
350
+ encoding: "utf8",
351
+ timeout: 2e3
352
+ }), ownMb, at);
353
+ } catch {}
354
+ }
355
+ const ownMb = rssMb();
356
+ const limitMb = totalMb();
357
+ if (!reading) return {
358
+ t,
359
+ availMb: os.freemem() / MB,
360
+ ownMb,
361
+ limitMb,
362
+ ageMs: 0,
363
+ source: "os"
364
+ };
365
+ return {
366
+ t,
367
+ availMb: Math.max(0, reading.availMb - (ownMb - reading.ownMb)),
368
+ ownMb,
369
+ limitMb,
370
+ ...pressureLevel ? { pressureLevel } : {},
371
+ ageMs: Math.max(0, performance.now() - reading.t),
372
+ source: "darwin"
373
+ };
374
+ },
375
+ close() {
376
+ closed = true;
377
+ clearTimeout(timer);
378
+ child?.kill();
379
+ }
380
+ };
381
+ }
382
+ /** GOATLY_TEST_MEMORY: a capacity by pages queried, the process's own memory taken from it */
383
+ function testSampler(steps, own) {
384
+ const limitMb = Math.max(...steps.map((step) => step[1]));
385
+ return {
386
+ sample(progress) {
387
+ const t = performance.now();
388
+ const ownMb = own();
389
+ const capacity = capacityAt(steps, progress?.queried ?? 0);
390
+ return {
391
+ t,
392
+ availMb: Math.max(0, capacity - ownMb),
393
+ ownMb,
394
+ limitMb,
395
+ ageMs: 0,
396
+ source: "test"
397
+ };
398
+ },
399
+ close() {}
400
+ };
401
+ }
402
+ function createSampler(options, poll) {
403
+ const env = options.env ?? process.env;
404
+ const platform = options.platform ?? process.platform;
405
+ const steps = env.GOATLY_TEST_MEMORY ? parseTestMemory(env.GOATLY_TEST_MEMORY) : [];
406
+ if (steps.length > 0) return testSampler(steps, ownMemory(platform, options.procRoot ?? "/proc"));
407
+ if (platform === "linux") return linuxSampler(options);
408
+ if (platform === "darwin") return darwinSampler(poll);
409
+ return {
410
+ sample: () => ({
411
+ t: performance.now(),
412
+ availMb: os.freemem() / MB,
413
+ ownMb: rssMb(),
414
+ limitMb: totalMb(),
415
+ ageMs: 0,
416
+ source: "os"
417
+ }),
418
+ close() {}
419
+ };
420
+ }
421
+ /**
422
+ * A sampler of the memory this process may still use (see MemorySample). Linux: the cgroup levels
423
+ * are found once, their files read on every sample – the lowest of MemAvailable and each level's
424
+ * headroom (limit − usage, page cache counted as free). macOS: `vm_stat` every second in the
425
+ * background (close() stops it). Elsewhere (Windows): os.freemem() only – no pressure, commit
426
+ * charge or job-object limit is read there. GOATLY_TEST_MEMORY (tests, every
427
+ * OS): a capacity by pages queried, see parseTestMemory.
428
+ */
429
+ function createMemorySampler(options = {}) {
430
+ return createSampler(options, true);
431
+ }
432
+ /** one sample, synchronously (macOS: runs `vm_stat`) */
433
+ function sampleMemoryOnce(options = {}) {
434
+ const sampler = createSampler(options, false);
435
+ try {
436
+ return sampler.sample();
437
+ } finally {
438
+ sampler.close();
439
+ }
440
+ }
441
+ export { capacityAt, createMemorySampler, findCgroupLevels, findMemoryCgroups, parseCgroupLimit, parseCgroupStat, parseMeminfo, parsePressureLevel, parsePsiSomeTotal, parseStatusRssAnonMb, parseTestMemory, parseVmStatAvailableMb, sampleMemoryOnce };