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,657 @@
1
+ import { parseVmStatAvailableMb, sampleMemoryOnce } from "./memory-signals.js";
2
+ import { PerformanceObserver, constants, performance } from "node:perf_hooks";
3
+ import os from "node:os";
4
+ import v8 from "node:v8";
5
+ import vm from "node:vm";
6
+ // src/node/utils/memory.ts
7
+ const MB = 1048576;
8
+ /**
9
+ * Memory (MB) the process can still use now (see sampleMemoryOnce): free + reclaimable memory, the
10
+ * lowest of the system's and every cgroup level's headroom on Linux (other processes in a container
11
+ * count, its clean page cache is free), Activity Monitor's "available" on macOS, os.freemem()
12
+ * elsewhere.
13
+ */
14
+ function availableMemoryMb() {
15
+ return Math.max(0, Math.floor(sampleMemoryOnce().availMb));
16
+ }
17
+ const isBun = typeof process.versions.bun === "string";
18
+ const RUNTIME = isBun ? "bun" : "node";
19
+ /** head room for the main thread (rendering, page-data, Vite) when workers are planned */
20
+ const MAIN_RESERVE_MB = 1024;
21
+ /** estimate for one render worker: the SSR bundle and one batch (measured 15–30 MB) – generous */
22
+ const RENDER_WORKER_MB = 256;
23
+ /** the smallest heap limit a replacement worker is started with (MB of free memory kept) */
24
+ const REPLACEMENT_RESERVE_MB = 512;
25
+ /** the smallest heap budget of a worker thread on Bun (with little free memory) */
26
+ const MIN_BUDGET_MB = 256;
27
+ /** memory (MB) of the machine, or of the container (cgroup limit) when that is smaller */
28
+ function totalMemoryMb() {
29
+ const total = os.totalmem();
30
+ const constrained = typeof process.constrainedMemory === "function" ? process.constrainedMemory() : 0;
31
+ return Math.floor((constrained > 0 && constrained < total ? constrained : total) / MB);
32
+ }
33
+ /** `--max-old-space-size=` as V8 accepts it (`-` or `_` between the words) */
34
+ const MAX_OLD_SPACE_SIZE = /^--max[-_]old[-_]space[-_]size=/;
35
+ /** `--max-old-space-size-percentage=` (Node 22.20+: a share of the memory, wins over the size) */
36
+ const MAX_OLD_SPACE_SIZE_PERCENTAGE = /^--max[-_]old[-_]space[-_]size[-_]percentage=/;
37
+ const unquote = (value) => value.replace(/^"(.*)"$/, "$1");
38
+ /** the value (MB) of the last `--max-old-space-size=<MB>` in `args`, 0: none */
39
+ function maxOldSpaceSizeArg(args) {
40
+ let value = 0;
41
+ for (const arg of args) if (MAX_OLD_SPACE_SIZE.test(arg)) value = Math.round(Number(unquote(arg.slice(arg.indexOf("=") + 1)))) || 0;
42
+ return value;
43
+ }
44
+ const nodeOptions = (env) => (env.NODE_OPTIONS ?? "").split(/\s+/).filter(Boolean).map(unquote);
45
+ /**
46
+ * The old generation limit (MB) `--max-old-space-size-percentage=<P>` gives every thread: P% of the
47
+ * memory (or of the container's limit), computed like Node does
48
+ */
49
+ function percentageLimitMb(args) {
50
+ let percentage = 0;
51
+ for (const arg of args) if (MAX_OLD_SPACE_SIZE_PERCENTAGE.test(arg)) percentage = Number(unquote(arg.slice(arg.indexOf("=") + 1))) || 0;
52
+ const total = os.totalmem();
53
+ const constrained = typeof process.constrainedMemory === "function" ? process.constrainedMemory() : 0;
54
+ return Math.floor((constrained > 0 && constrained < total ? constrained : total) * percentage / 100 / MB);
55
+ }
56
+ /**
57
+ * The heap limit (MB) the user chose for Node: `--max-old-space-size` in NODE_OPTIONS or the node
58
+ * arguments (the latter win), or GOATLY_HEAP_LIMIT=<MB>. The `--max-old-space-size` the bin
59
+ * sets when it restarts Node (GOATLY_RESPAWNED) is not one: the bin only restarts Node when
60
+ * the user chose no limit. On Bun only GOATLY_HEAP_LIMIT counts: Bun ignores V8's flags,
61
+ * also in NODE_OPTIONS.
62
+ */
63
+ function userHeapLimit(env = process.env, execArgv = process.execArgv, runtime = RUNTIME) {
64
+ if (runtime === "node" && !env.GOATLY_RESPAWNED) {
65
+ const args = [...nodeOptions(env), ...execArgv];
66
+ const share = percentageLimitMb(args);
67
+ if (share > 0) return {
68
+ mb: share,
69
+ source: "--max-old-space-size-percentage"
70
+ };
71
+ const flag = maxOldSpaceSizeArg(args);
72
+ if (flag > 0) return {
73
+ mb: flag,
74
+ source: "--max-old-space-size"
75
+ };
76
+ }
77
+ const setting = Number(env.GOATLY_HEAP_LIMIT);
78
+ return setting > 0 ? {
79
+ mb: Math.round(setting),
80
+ source: "GOATLY_HEAP_LIMIT"
81
+ } : void 0;
82
+ }
83
+ /**
84
+ * The heap limit (MB) Node gives a thread on this machine when nobody chose one: half the memory, up
85
+ * to about 2 GB (4 GB with 15 GB of memory or more; V8 12). The bin measures it before it restarts
86
+ * Node with a larger limit (GOATLY_NODE_HEAP_MB): afterwards no thread can see it.
87
+ */
88
+ function nodeDefaultHeapMb(env = process.env, execArgv = process.execArgv) {
89
+ const measured = Number(env.GOATLY_NODE_HEAP_MB);
90
+ if (measured > 0) return Math.round(measured);
91
+ if (!env.GOATLY_RESPAWNED && !userHeapLimit({
92
+ ...env,
93
+ GOATLY_HEAP_LIMIT: ""
94
+ }, execArgv)) return Math.round(v8.getHeapStatistics().heap_size_limit / MB);
95
+ const total = totalMemoryMb();
96
+ return Math.min(Math.floor(total / 2), total >= 15360 ? 4096 : 2048) + 48;
97
+ }
98
+ /**
99
+ * The heap limit of `workers` worker threads, in this order:
100
+ * 1. GOATLY_WORKER_HEAP_MB
101
+ * 2. the limit the user chose for Node (see userHeapLimit) – as in plain Node, it applies to every
102
+ * thread
103
+ * 3. otherwise an equal share of the free memory among the workers and the main thread, never less
104
+ * than Node's own default (or `minMb`, e.g. for workers that copy the data layer).
105
+ *
106
+ * A limit is a ceiling, not memory set aside: with `--heap-growing-percent` (configureBuildHeap) a
107
+ * heap stays close to its live size whatever the limit, so a generous limit costs no memory – but a
108
+ * low one fails builds V8 would complete. Without it (GOATLY_HEAP_GROWING_PERCENT=0, or
109
+ * GOATLY_HEAP_LIMIT=off) workers get Node's default.
110
+ * A replacement worker gets twice the limit, then the main thread's (both at most the memory that is
111
+ * free when it starts) unless the user chose a limit.
112
+ *
113
+ * On Bun these are budgets (`soft`, see WorkerHeap): GOATLY_WORKER_HEAP_MB,
114
+ * GOATLY_HEAP_LIMIT, or else the share of the free memory, without Node's default as the
115
+ * floor – a budget fails nothing, and the budgets of workers that stay within them fit into the free
116
+ * memory together, the main thread's reserve left (unless `minMb`, the estimated heap of a worker
117
+ * that copies the data layer, is larger). V8's growth settings don't apply.
118
+ */
119
+ function planWorkerHeap(options) {
120
+ const env = options.env ?? process.env;
121
+ const execArgv = options.execArgv ?? process.execArgv;
122
+ const runtime = options.runtime ?? RUNTIME;
123
+ const soft = runtime === "bun";
124
+ const fixed = (mb, source, budgetMb) => ({
125
+ limitMb: mb,
126
+ ladder: [
127
+ mb,
128
+ mb,
129
+ mb
130
+ ],
131
+ source,
132
+ ...soft ? { soft: true } : {},
133
+ ...budgetMb !== void 0 && budgetMb < mb ? { budgetMb } : {}
134
+ });
135
+ let available;
136
+ /** an equal share of the free memory among the workers and the main thread (its reserve left) */
137
+ const share = () => {
138
+ available ??= options.availableMb ?? availableMemoryMb();
139
+ const mb = Math.floor((available - MAIN_RESERVE_MB) / (Math.max(1, options.workers) + 1));
140
+ return Math.max(MIN_BUDGET_MB, Math.ceil(options.minMb ?? 0), mb);
141
+ };
142
+ const override = Number(env.GOATLY_WORKER_HEAP_MB);
143
+ if (override > 0) return fixed(Math.round(override), "GOATLY_WORKER_HEAP_MB");
144
+ const user = userHeapLimit(env, execArgv, runtime);
145
+ if (user) return fixed(user.mb, user.source, soft ? void 0 : share());
146
+ if (soft) return fixed(share(), "default");
147
+ const floor = Math.max(options.nodeDefaultMb ?? nodeDefaultHeapMb(env, execArgv), Math.ceil(options.minMb ?? 0));
148
+ const growing = Number(env.GOATLY_HEAP_GROWING_PERCENT ?? 50);
149
+ let first = floor;
150
+ if (env.GOATLY_HEAP_LIMIT !== "off" && growing > 0) first = Math.max(floor, share());
151
+ const start = Number(env.GOATLY_WORKER_HEAP_START_MB);
152
+ if (start > 0) first = Math.round(start);
153
+ const main = options.mainMb ?? Math.round(v8.getHeapStatistics().heap_size_limit / MB);
154
+ const budgetMb = env.GOATLY_HEAP_LIMIT === "off" ? void 0 : share();
155
+ return {
156
+ limitMb: first,
157
+ ladder: [
158
+ first,
159
+ 2 * first,
160
+ Math.max(2 * first, main)
161
+ ],
162
+ source: "default",
163
+ ...budgetMb !== void 0 && budgetMb < first ? { budgetMb } : {}
164
+ };
165
+ }
166
+ /** the heap (MB) a worker measures itself against: its budget, else its limit */
167
+ function workerBudgetMb(heap, limitMb) {
168
+ if (heap.soft) return limitMb;
169
+ return heap.budgetMb !== void 0 && limitMb !== void 0 ? Math.min(heap.budgetMb, limitMb) : limitMb;
170
+ }
171
+ /** e.g. "heap limit 2869 MB (default)", "heap budget 2869 MB (default)" (Bun), for messages */
172
+ function heapText(heap) {
173
+ if (heap.limitMb === void 0) return "no heap limit";
174
+ const budget = heap.budgetMb !== void 0 ? `, budget ${heap.budgetMb} MB` : "";
175
+ return `heap ${heap.soft ? "budget" : "limit"} ${heap.limitMb} MB${budget} (${heap.source})`;
176
+ }
177
+ /**
178
+ * The heap limit (MB) of a worker of attempt `rung` (0: the first, then replacements): replacements
179
+ * get at most the memory that is free when they start – never less than the first limit.
180
+ */
181
+ function workerLimitMb(heap, rung) {
182
+ if (heap.limitMb === void 0) return void 0;
183
+ const ladder = heap.ladder;
184
+ const wanted = ladder[Math.min(rung, ladder.length - 1)];
185
+ if (rung === 0 || wanted <= ladder[0]) return ladder[0];
186
+ return Math.max(ladder[0], Math.min(wanted, availableMemoryMb() - REPLACEMENT_RESERVE_MB));
187
+ }
188
+ /**
189
+ * What to do when a worker thread keeps running out of memory (for error messages). `triedMb`: the
190
+ * highest heap limit a worker had – building in the main thread is only suggested when its limit is
191
+ * higher.
192
+ */
193
+ function outOfMemoryHint(heap, triedMb = heap.limitMb ?? 0) {
194
+ if (heap.soft) return "Bun has no heap limit per thread: worker threads only drop their caches when their heaps reach their budgets (GOATLY_WORKER_HEAP_MB=<MB> sets it). Fewer worker threads (`renderWorkers` in gatsby-config, or GOATLY_RENDER_WORKERS=<n>) need less memory.";
195
+ const mainMb = Math.round(v8.getHeapStatistics().heap_size_limit / MB);
196
+ const mainThread = (heap.source === "default" || heap.source === "GOATLY_WORKER_HEAP_MB") && mainMb > triedMb + 256 ? ` \`renderWorkers: 1\` in gatsby-config (or GOATLY_RENDER_WORKERS=1 when it doesn't set renderWorkers) builds all pages in the main thread instead (heap limit ${mainMb} MB).` : "";
197
+ if (heap.source === "GOATLY_WORKER_HEAP_MB") return `The limit comes from GOATLY_WORKER_HEAP_MB: raise it.${mainThread}`;
198
+ if (heap.source !== "default") return `Worker threads get the limit you set with ${heap.source}: raise it, or set GOATLY_WORKER_HEAP_MB=<MB> (worker threads only).${mainThread}`;
199
+ return `That is about as much as a worker thread gets here: the page, or code that runs for it, needs too much memory (e.g. a very large query result, or an endless loop). GOATLY_WORKER_HEAP_MB=<MB> sets the heap limit of worker threads.${mainThread}`;
200
+ }
201
+ /**
202
+ * what a query worker needs (MB) when its page queries run in WASM, until it reports what it uses
203
+ * (see memory-governor.ts): the nodes are in the main thread's shared store, a worker's heap holds
204
+ * its renderer and its pages' results – measured 35–80 MB of heap (20k–100k pages, ~140 MB at
205
+ * 400k) and ~90 MB of RSS per worker (100k pages); 1.25 × 140 + 32 MB rounded up
206
+ */
207
+ const WASM_QUERY_WORKER_MB = 256;
208
+ /**
209
+ * How many query workers fit into the available memory. Every worker rebuilds the data layer –
210
+ * about as large as the main thread's heap after bootstrap – unless the datastore is shared
211
+ * between threads (`lazy` stores read nodes on demand).
212
+ */
213
+ function planQueryWorkers(options) {
214
+ const perWorkerMb = options.sharedDatastore ? 512 : Math.max(512, Math.ceil(options.heapUsedMb * 1.25 + 256));
215
+ const availableMb = options.availableMb ?? availableMemoryMb();
216
+ const fit = Math.max(0, Math.floor((availableMb - MAIN_RESERVE_MB) / perWorkerMb));
217
+ const count = Math.min(options.wanted, fit);
218
+ return {
219
+ count,
220
+ perWorkerMb,
221
+ heap: planWorkerHeap({
222
+ ...options,
223
+ availableMb,
224
+ workers: count,
225
+ minMb: options.sharedDatastore ? 0 : Math.ceil(perWorkerMb * 1.5)
226
+ })
227
+ };
228
+ }
229
+ /**
230
+ * How many render workers to start for `batches` batches of pages: at most one per batch and as
231
+ * many as fit into the available memory (fewer than 2: render in the main thread).
232
+ */
233
+ function planRenderWorkers(options) {
234
+ const availableMb = options.availableMb ?? availableMemoryMb();
235
+ const fit = Math.floor((availableMb - MAIN_RESERVE_MB) / RENDER_WORKER_MB);
236
+ const count = Math.max(1, Math.min(options.wanted, options.batches, fit));
237
+ return {
238
+ count,
239
+ heap: planWorkerHeap({
240
+ ...options,
241
+ availableMb,
242
+ workers: count
243
+ })
244
+ };
245
+ }
246
+ /**
247
+ * V8 settings for a build (Node only, process-wide, read by isolates created afterwards):
248
+ * - a `--max-old-space-size` of the process (e.g. the bin's 75% of the memory) would be every
249
+ * worker's limit and override their `resourceLimits`: reset – every build worker gets explicit
250
+ * limits from planWorkerHeap, which applies a limit the user chose to the workers, too
251
+ * - V8 lets a heap grow to about 4× its live size before a major GC once its limit is 2 GB or more;
252
+ * `--heap-growing-percent` keeps heaps closer to their live size (GOATLY_HEAP_GROWING_PERCENT,
253
+ * 0: V8's default)
254
+ * (Bun: JavaScriptCore's heap growth is kept – limiting it with BUN_JSC_* settings cost more time
255
+ * than it saved memory; a smaller worker budget is the better lever, see planWorkerHeap)
256
+ */
257
+ function configureBuildHeap() {
258
+ if (isBun) return;
259
+ try {
260
+ v8.setFlagsFromString("--max-old-space-size=0");
261
+ const growing = Number(process.env.GOATLY_HEAP_GROWING_PERCENT ?? 50);
262
+ if (growing > 0) v8.setFlagsFromString(`--heap-growing-percent=${Math.round(growing)}`);
263
+ } catch {}
264
+ }
265
+ /**
266
+ * used heap / heap limit of this thread – / `budgetMb` when that is smaller (a worker's share of
267
+ * the free memory, see WorkerHeap). Bun: / `budgetMb`, the worker's budget (0 without one).
268
+ * Its heap in use is the larger of `heapUsed` (the live objects as of the last collection, plus
269
+ * strings and buffers at once) and `heapTotal` (the heap's blocks, garbage included – down to the
270
+ * live objects after `Bun.gc(true)`, see collectGarbage), like V8's used heap. (Not
271
+ * `v8.getHeapStatistics()`: on Bun it walks the whole heap, tens of milliseconds per million
272
+ * objects, and its limit is 10× the process's peak memory.)
273
+ */
274
+ function heapRatio(budgetMb, runtime = RUNTIME, usage = () => process.memoryUsage()) {
275
+ if (runtime === "bun") {
276
+ if (!budgetMb) return 0;
277
+ const { heapUsed, heapTotal } = usage();
278
+ return Math.max(heapUsed, heapTotal) / (budgetMb * MB);
279
+ }
280
+ const heap = v8.getHeapStatistics();
281
+ const limit = budgetMb && budgetMb * MB < heap.heap_size_limit ? budgetMb * MB : heap.heap_size_limit;
282
+ return heap.used_heap_size / limit;
283
+ }
284
+ /**
285
+ * The heap (MB) this thread uses: V8's used heap; Bun: the larger of `heapUsed` and `heapTotal`
286
+ * (see heapRatio)
287
+ */
288
+ function heapUsedMb(runtime = RUNTIME) {
289
+ if (runtime === "bun") {
290
+ const { heapUsed, heapTotal } = process.memoryUsage();
291
+ return Math.max(heapUsed, heapTotal) / MB;
292
+ }
293
+ return v8.getHeapStatistics().used_heap_size / MB;
294
+ }
295
+ /** batches between two releases of a query worker's caches, at least and at most */
296
+ const RELEASE_SPACING = 8;
297
+ const MAX_RELEASE_SPACING = 64;
298
+ /** a release freed little when it freed less than this share of the heap */
299
+ const FUTILE_RELEASE = .1;
300
+ /**
301
+ * a release didn't last when the heap is back at this share of what it was: the worker needs what
302
+ * was dropped. It lasted when the heap is still below that this many batches later.
303
+ */
304
+ const REBOUND = .9;
305
+ const REBOUND_WINDOW = 64;
306
+ /**
307
+ * the most of a worker's time its heap guard spends on the collections it forces for a budget –
308
+ * and what they may take in any case (ms: a worker that just started has no time to take a share
309
+ * of)
310
+ */
311
+ const FORCED_GC_SHARE = .05;
312
+ const FORCED_GC_GRACE_MS = 250;
313
+ /**
314
+ * a budget is a worker's heap limit, for its heap guard, when the limit is less than this multiple
315
+ * of it: then there is no room above the budget to keep caches in
316
+ */
317
+ const BUDGET_IS_LIMIT = 1.25;
318
+ /** the share of a heap limit up to which a worker may keep the caches it needs */
319
+ const NEAR_HEAP_LIMIT = .7;
320
+ /**
321
+ * The heap in use (a share of the budget) at which a query worker's heap guard collects garbage
322
+ * for a budget below its heap limit, `live` being what the last collection left: at 70%, and never
323
+ * before garbage could be 15% of the budget or a quarter of the live heap. Garbage is what a
324
+ * collection frees, and a collection costs time by the live heap: with less room than that, a heap
325
+ * that is nearly all live data would be collected over and over for the little garbage a few pages
326
+ * leave.
327
+ */
328
+ function heapCollectAt(live) {
329
+ return Math.max(.7, live + Math.max(.15, .25 * live));
330
+ }
331
+ /**
332
+ * The live heap (a share of the budget) at which a query worker drops its caches: 70%, or 15% more
333
+ * than the last release left (`floor`), at most 85%. With a budget below the heap limit (`ceiling`:
334
+ * the limit as a multiple of the budget), a worker whose heap came back after a release needs what
335
+ * was dropped (`need`): its caches stay until the heap is 15% above that – up to 70% of the heap
336
+ * limit, or `hold` (a share of the budget) when that is less.
337
+ */
338
+ function heapReleaseAt(floor, need = 0, ceiling = 1, hold = 1e400) {
339
+ const full = Math.min(.85, Math.max(.7, floor + .15));
340
+ if (ceiling < BUDGET_IS_LIMIT) return full;
341
+ return Math.max(full, Math.min(need + .15, NEAR_HEAP_LIMIT * ceiling, hold));
342
+ }
343
+ /**
344
+ * The heap guard of a heap limit (see createHeapGuard): at 70% of the limit in use – live + 15%
345
+ * when the last release left more, at most 85% – at most every `spacing` batches (8, doubled up to
346
+ * 64 while releases free less than 10%), at 85% at once (unless the last release freed little). A
347
+ * GC runs first: when it frees enough, the pressure was garbage and the caches stay (checks are
348
+ * spaced out further).
349
+ */
350
+ function createLimitGuard(o) {
351
+ let since = 1e400;
352
+ let live = 0;
353
+ let spacing = RELEASE_SPACING;
354
+ let futile = false;
355
+ return {
356
+ /** forgets what the last checks found: the next batch is checked */
357
+ reset() {
358
+ since = 1e400;
359
+ live = 0;
360
+ spacing = RELEASE_SPACING;
361
+ futile = false;
362
+ },
363
+ /** what it did: dropped the caches, or collected garbage (the caches stay) */
364
+ afterBatch() {
365
+ since++;
366
+ let used = o.ratio();
367
+ const threshold = Math.min(.85, Math.max(.7, live + .15));
368
+ if (!(used >= threshold && (since >= spacing || used >= .85 && !futile))) return void 0;
369
+ o.gc(false);
370
+ used = o.ratio();
371
+ since = 0;
372
+ if (used < threshold) {
373
+ live = used;
374
+ spacing = Math.min(MAX_RELEASE_SPACING, spacing * 2);
375
+ return "collected";
376
+ }
377
+ o.release();
378
+ o.gc(true);
379
+ const after = o.ratio();
380
+ futile = used - after < FUTILE_RELEASE;
381
+ spacing = futile ? Math.min(MAX_RELEASE_SPACING, spacing * 2) : RELEASE_SPACING;
382
+ live = after;
383
+ return "released";
384
+ }
385
+ };
386
+ }
387
+ /**
388
+ * Drops what a query worker only keeps for reuse (`release`: query engine caches, plugin cache
389
+ * entries, decoded nodes) when live data fills its heap, then collects garbage. Called between
390
+ * batches (nothing in flight). Those caches are bounded by entries, not bytes: large nodes or many
391
+ * views of a large type could otherwise run a worker out of memory.
392
+ *
393
+ * `ratio` measures the heap against the worker's budget (heapRatio), `ceiling` tells its heap limit
394
+ * as a multiple of that. Two rules apply:
395
+ *
396
+ * - **The heap limit** (createLimitGuard), where V8 itself would run out of memory: at 70–85% of
397
+ * it the caches are dropped, at most every 8 batches while that frees memory. It is the only rule
398
+ * when the budget is the limit, or close to it (less than 25% below), and on Bun, whose threads
399
+ * have no limit but the budget (`ceiling` 1).
400
+ * - **A budget below the limit** – a worker's share of the free memory – is not where the worker
401
+ * runs out of memory, and what the guard does for it is paid by the live heap: a forced
402
+ * collection takes about a third of a second per GB, and what a release dropped is built again
403
+ * by the next queries that need it. So for a budget:
404
+ * - The heap in use includes garbage, and only a collection tells how much. V8's own collections
405
+ * tell an upper bound (`collected`); the guard forces one when garbage could be a good part of
406
+ * the heap (heapCollectAt) – not for the garbage of a few rendered pages – or when a release
407
+ * is due, and not while forced collections have taken more than 5% of the worker's time.
408
+ * - The caches are dropped when the live heap reaches heapReleaseAt, at most every 8 batches. A
409
+ * release that freed less than 10% had nothing to free: the next one waits twice as long (up
410
+ * to 64 batches). One after which the heap is back where it was dropped what the worker needs:
411
+ * the next one waits twice as long, too, and only happens once the heap is 15% above what it
412
+ * came back to (at most 70% of the heap limit, or `hold`). A worker whose data needs more than
413
+ * its budget so stays above it instead of building its caches again every few batches – the
414
+ * adaptive pool sees its heap, and gives it a larger budget or retires a worker.
415
+ *
416
+ * `rescale` follows a budget that changed. On Bun without a budget `ratio` is 0 and nothing is
417
+ * released.
418
+ * (GOATLY_HEAP_GUARD=off|always: internal, for tests)
419
+ */
420
+ function createHeapGuard(options) {
421
+ const mode = (options.env ?? process.env).GOATLY_HEAP_GUARD;
422
+ const ratio = options.ratio ?? heapRatio;
423
+ const gc = options.gc ?? ((full) => collectGarbage(full));
424
+ const now = options.now ?? (() => performance.now());
425
+ const started = now();
426
+ /** batches since the last release */
427
+ let since = 1e400;
428
+ /** the heap in use after the last collection known of (forced, or V8's own) */
429
+ let live = 0;
430
+ let known = false;
431
+ /** what the last release left, and what the heap came back to after one */
432
+ let floor = 0;
433
+ let need = 0;
434
+ let spacing = RELEASE_SPACING;
435
+ /** the last release, while it is not known whether it lasted: the live heap before it */
436
+ let dropped;
437
+ let releases = 0;
438
+ let checks = 0;
439
+ let skipped = 0;
440
+ let forcedMs = 0;
441
+ const ceiling = () => Math.max(1, options.ceiling?.() ?? 1);
442
+ const releaseAt = () => heapReleaseAt(floor, need, ceiling(), options.hold?.());
443
+ const collect = (full) => {
444
+ const start = now();
445
+ gc(full);
446
+ forcedMs += now() - start;
447
+ checks++;
448
+ };
449
+ const release = () => {
450
+ options.release();
451
+ releases++;
452
+ };
453
+ /**
454
+ * the rule of the heap limit: against the limit itself (`limitScale`: the limit as a multiple of
455
+ * the budget), or against a budget that is the limit (1)
456
+ */
457
+ let limitScale = 1;
458
+ const limit = createLimitGuard({
459
+ ratio: () => ratio() / limitScale,
460
+ release,
461
+ gc: collect
462
+ });
463
+ /** how far a budget that is the limit was lowered since the limit's rule last looked */
464
+ let lowered = 1;
465
+ /** the release lasted: the heap stayed below what it was */
466
+ const lasted = () => {
467
+ dropped = void 0;
468
+ need = 0;
469
+ spacing = RELEASE_SPACING;
470
+ };
471
+ /** `exact`: measured right after a collection (not an upper bound, with the garbage since) */
472
+ const learn = (value, exact) => {
473
+ live = value;
474
+ known = true;
475
+ if (!exact || dropped === void 0) return;
476
+ if (value < REBOUND * dropped) {
477
+ if (since >= REBOUND_WINDOW) lasted();
478
+ return;
479
+ }
480
+ need = Math.max(need, value);
481
+ spacing = Math.min(MAX_RELEASE_SPACING, spacing * 2);
482
+ dropped = void 0;
483
+ };
484
+ return {
485
+ get releases() {
486
+ return releases;
487
+ },
488
+ /** the collections it forced so far */
489
+ get checks() {
490
+ return checks;
491
+ },
492
+ /** checks left out because forced collections had taken their share of the time */
493
+ get skipped() {
494
+ return skipped;
495
+ },
496
+ /** ms spent in forced collections */
497
+ get forcedMs() {
498
+ return forcedMs;
499
+ },
500
+ /** the share of the heap in use after the last collection known of, 0: none yet */
501
+ get live() {
502
+ return known ? live : 0;
503
+ },
504
+ /**
505
+ * The budget it measures against changed by `factor` (old / new): what it knows about the heap
506
+ * stays true. A lower budget applies from the next batch – what holds a release back still
507
+ * does: the batches since the last one, the time forced collections took, and what the worker
508
+ * showed it needs (a release that didn't last is not tried again for a lower budget). A budget
509
+ * that is the heap limit is checked at once when it was lowered by a tenth.
510
+ */
511
+ rescale(factor) {
512
+ if (!(factor > 0) || factor === 1) return;
513
+ live *= factor;
514
+ floor *= factor;
515
+ need *= factor;
516
+ if (dropped !== void 0) dropped *= factor;
517
+ lowered = Math.max(1, lowered * factor);
518
+ },
519
+ afterBatch() {
520
+ if (mode === "off") return;
521
+ since++;
522
+ if (mode === "always") {
523
+ release();
524
+ collect(true);
525
+ return;
526
+ }
527
+ const scale = ceiling() < BUDGET_IS_LIMIT ? 1 : ceiling();
528
+ if (scale !== limitScale) limit.reset();
529
+ else if (scale === 1 && lowered >= 1 / .9) {
530
+ limit.reset();
531
+ lowered = 1;
532
+ }
533
+ limitScale = scale;
534
+ const acted = limit.afterBatch();
535
+ if (acted || scale === 1) {
536
+ if (!acted) return;
537
+ lowered = 1;
538
+ const left = ratio();
539
+ if (acted === "released") {
540
+ floor = left;
541
+ dropped = void 0;
542
+ since = 0;
543
+ }
544
+ live = left;
545
+ known = true;
546
+ return;
547
+ }
548
+ let used = ratio();
549
+ if (dropped !== void 0 && since >= REBOUND_WINDOW && used < REBOUND * dropped) lasted();
550
+ const seen = options.collected?.();
551
+ if (seen !== void 0) learn(Math.min(seen, used), false);
552
+ const garbage = used >= heapCollectAt(live);
553
+ const due = known && live >= releaseAt() && since >= spacing;
554
+ if (!garbage && !due) return;
555
+ if (forcedMs > FORCED_GC_GRACE_MS + FORCED_GC_SHARE * (now() - started)) {
556
+ skipped++;
557
+ return;
558
+ }
559
+ collect(false);
560
+ used = ratio();
561
+ learn(used, true);
562
+ if (used < releaseAt() || since < spacing) return;
563
+ release();
564
+ collect(true);
565
+ const after = ratio();
566
+ if (used - after < FUTILE_RELEASE) {
567
+ spacing = Math.min(MAX_RELEASE_SPACING, spacing * 2);
568
+ dropped = void 0;
569
+ } else dropped = used;
570
+ floor = live = after;
571
+ known = true;
572
+ since = 0;
573
+ }
574
+ };
575
+ }
576
+ /**
577
+ * Watches the garbage collections V8 runs on its own in this thread (perf_hooks' "gc" entries).
578
+ * Node reports them when the event loop turns, in the order they ran – so often after the work
579
+ * they interrupted. The collections `collectGarbage` forces are left out (by their flag – which a
580
+ * full one doesn't have – and by when they ran): who forces them measures them. Without the
581
+ * entries (Bun) nothing is reported.
582
+ */
583
+ function watchGarbageCollections(onCollection) {
584
+ let observer;
585
+ const take = (entries) => {
586
+ for (const entry of entries) {
587
+ const detail = entry.detail;
588
+ if (!detail) continue;
589
+ if (((detail.flags ?? 0) & constants.NODE_PERFORMANCE_GC_FLAGS_FORCED) !== 0) continue;
590
+ const start = entry.startTime;
591
+ if (forcedCollections.some(([from, to]) => start >= from && start <= to)) continue;
592
+ onCollection({
593
+ start: entry.startTime,
594
+ ms: entry.duration,
595
+ major: detail.kind === constants.NODE_PERFORMANCE_GC_MAJOR
596
+ });
597
+ }
598
+ };
599
+ try {
600
+ if (!isBun) {
601
+ observer = new PerformanceObserver((list) => take(list.getEntries()));
602
+ observer.observe({ entryTypes: ["gc"] });
603
+ }
604
+ } catch {
605
+ observer = void 0;
606
+ }
607
+ return { close() {
608
+ observer?.disconnect();
609
+ observer = void 0;
610
+ } };
611
+ }
612
+ /**
613
+ * The CPU time (ms) this thread used so far (`process.threadCpuUsage`), or undefined where the
614
+ * runtime doesn't measure it per thread
615
+ */
616
+ function threadCpuMs() {
617
+ try {
618
+ const usage = process.threadCpuUsage?.();
619
+ return usage ? (usage.user + usage.system) / 1e3 : void 0;
620
+ } catch {
621
+ return;
622
+ }
623
+ }
624
+ /** when this thread last forced collections (performance.now(): from, to), see collectGarbage */
625
+ const forcedCollections = [];
626
+ /**
627
+ * A full, memory-reducing GC (releases heap pages, not only objects) – e.g. before workers start.
628
+ * `full = false`: a plain major GC.
629
+ */
630
+ function collectGarbage(full = true) {
631
+ const from = performance.now();
632
+ try {
633
+ collect(full);
634
+ } finally {
635
+ forcedCollections.push([from, performance.now()]);
636
+ if (forcedCollections.length > 32) forcedCollections.shift();
637
+ }
638
+ }
639
+ function collect(full) {
640
+ try {
641
+ if (isBun) {
642
+ globalThis.Bun?.gc?.(true);
643
+ return;
644
+ }
645
+ let gc = globalThis.gc;
646
+ if (typeof gc !== "function") {
647
+ v8.setFlagsFromString("--expose-gc");
648
+ gc = vm.runInNewContext("gc");
649
+ }
650
+ gc({
651
+ type: "major",
652
+ execution: "sync",
653
+ ...full ? { flavor: "last-resort" } : {}
654
+ });
655
+ } catch {}
656
+ }
657
+ export { RUNTIME, WASM_QUERY_WORKER_MB, availableMemoryMb, collectGarbage, configureBuildHeap, createHeapGuard, heapCollectAt, heapRatio, heapReleaseAt, heapText, heapUsedMb, maxOldSpaceSizeArg, nodeDefaultHeapMb, outOfMemoryHint, parseVmStatAvailableMb, planQueryWorkers, planRenderWorkers, planWorkerHeap, threadCpuMs, totalMemoryMb, userHeapLimit, watchGarbageCollections, workerBudgetMb, workerLimitMb };
@@ -0,0 +1,32 @@
1
+ // src/node/utils/murmurhash.ts
2
+ /**
3
+ * MurmurHash2 (32-bit) as used by Gatsby (`babel-plugin-remove-graphql-queries`)
4
+ * to compute static query hashes. Kept identical so `staticQueryHashes` match.
5
+ */
6
+ function murmurhash(str, seed) {
7
+ let l = str.length;
8
+ let h = seed ^ l;
9
+ let i = 0;
10
+ let k;
11
+ while (l >= 4) {
12
+ k = str.charCodeAt(i) & 255 | (str.charCodeAt(++i) & 255) << 8 | (str.charCodeAt(++i) & 255) << 16 | (str.charCodeAt(++i) & 255) << 24;
13
+ k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
14
+ k ^= k >>> 24;
15
+ k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
16
+ h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16) ^ k;
17
+ l -= 4;
18
+ ++i;
19
+ }
20
+ switch (l) {
21
+ case 3: h ^= (str.charCodeAt(i + 2) & 255) << 16;
22
+ case 2: h ^= (str.charCodeAt(i + 1) & 255) << 8;
23
+ case 1:
24
+ h ^= str.charCodeAt(i) & 255;
25
+ h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
26
+ }
27
+ h ^= h >>> 13;
28
+ h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
29
+ h ^= h >>> 15;
30
+ return h >>> 0;
31
+ }
32
+ export { murmurhash };