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,277 @@
1
+ import { SITE_PAGE_ID_PREFIX, getDataStore, getSitePageReadWatcher, watchSitePageReads } from "./datastore/index.js";
2
+ import "./query/dependencies.js";
3
+ import { writeFileIfChanged } from "./cache-layout.js";
4
+ import { store } from "./redux/index.js";
5
+ import { getNodeChangeCount } from "./redux/node-changes.js";
6
+ import reporter from "./reporter.js";
7
+ import { createContentDigest } from "./utils/content-digest.js";
8
+ import { isMainThread } from "node:worker_threads";
9
+ import path from "node:path";
10
+ import fs from "node:fs";
11
+ // src/node/site-page-nodes.ts
12
+ /**
13
+ * SitePage nodes (Gatsby's internal-data-bridge creates one per page; sites query them as
14
+ * `allSitePage` / `sitePage`, e.g. gatsby-plugin-sitemap in onPostBuild) cost every build a content
15
+ * digest and a datastore write per page (a touch on warm builds), and most sites never read them.
16
+ * So they are created once something can read them:
17
+ *
18
+ * - Until then createPage creates none. The first read – a query or `nodeModel` call on nodes of
19
+ * type SitePage (also through an interface or union), `getNode("SitePage …")`,
20
+ * `getNodesByType("SitePage")`, `getNodes()`, a node action on a SitePage node – creates the nodes
21
+ * of all pages created so far, in one batch and in page order, before the read is answered. From
22
+ * then on createPage creates them, as before.
23
+ * - Page and static queries that select SitePage nodes are found when they are compiled (before
24
+ * query workers get the nodes).
25
+ * - Query workers can't create nodes: a page whose query reads SitePage nodes in a worker whose
26
+ * nodes have none (e.g. a resolver calling `nodeModel.findAll({ type: "SitePage" })`) is built
27
+ * again once the main thread created them (see `createSitePageDeferrals`).
28
+ * - Whether they were read is kept in `.cache` with the nodes: a build after one that read them
29
+ * creates them from the start (warm builds touch them like before), and the persisted SitePage
30
+ * nodes of a build that did not read them are deleted (once).
31
+ *
32
+ * GOATLY_LAZY_SITE_PAGE_NODES=false creates them from the start in every build (as before).
33
+ */
34
+ const PLUGIN = { name: "internal-data-bridge" };
35
+ const RECORD_VERSION = 1;
36
+ /** `false`: createPage creates SitePage nodes from the start (for read paths that aren't noticed) */
37
+ const LAZY_SITE_PAGE_NODES_ENV = "GOATLY_LAZY_SITE_PAGE_NODES";
38
+ let state = initialState();
39
+ function initialState() {
40
+ return {
41
+ created: false,
42
+ read: false,
43
+ dependedOn: false,
44
+ materialized: 0,
45
+ worker: isMainThread ? void 0 : {
46
+ available: false,
47
+ misses: 0
48
+ }
49
+ };
50
+ }
51
+ function onRead(read) {
52
+ const worker = state.worker;
53
+ if (worker) {
54
+ state.read = true;
55
+ if (worker.available) watchSitePageReads(null);
56
+ else worker.misses++;
57
+ return;
58
+ }
59
+ watchSitePageReads(null);
60
+ if (!state.read) {
61
+ state.read = true;
62
+ reporter.verbose(`SitePage nodes are read (${read})`);
63
+ }
64
+ if (!state.created) createNodesOfExistingPages(read);
65
+ }
66
+ /**
67
+ * Starts the SitePage nodes of a build or develop process (main thread), once the persisted nodes
68
+ * are restored (`restored`): createPage creates them from the start when the build that persisted
69
+ * them read them, or with GOATLY_LAZY_SITE_PAGE_NODES=false.
70
+ */
71
+ function startSitePageNodes(options) {
72
+ state.worker = void 0;
73
+ if (process.env["GOATLY_LAZY_SITE_PAGE_NODES"] === "false") {
74
+ state.created = true;
75
+ reporter.verbose(`SitePage nodes are created up front (${LAZY_SITE_PAGE_NODES_ENV}=false)`);
76
+ } else if (options.restored && readSitePageRecord(options.cacheDir)) {
77
+ state.created = true;
78
+ reporter.verbose("SitePage nodes are created up front: the previous build read them");
79
+ }
80
+ watchSitePageReads(state.read && state.created ? null : onRead);
81
+ }
82
+ /** query workers: whether the nodes they loaded include SitePage nodes */
83
+ function startWorkerSitePageNodes(options) {
84
+ state = initialState();
85
+ state.worker = {
86
+ available: options.available,
87
+ misses: 0
88
+ };
89
+ watchSitePageReads(onRead);
90
+ }
91
+ /** a fresh state (tests: with a fresh store) */
92
+ function resetSitePageNodes() {
93
+ state = initialState();
94
+ watchSitePageReads(onRead);
95
+ }
96
+ /** something read SitePage nodes (e.g. a query worker): they are created now, if they aren't yet */
97
+ function readSitePageNodes(read) {
98
+ if (!state.worker && !(state.read && state.created)) onRead(read);
99
+ }
100
+ /** createPage creates SitePage nodes (they were read, or wanted from the start) */
101
+ function sitePageNodesCreated() {
102
+ return state.created;
103
+ }
104
+ /** whether SitePage nodes were read in this process (a query worker: since it started) */
105
+ function sitePageNodesWereRead() {
106
+ return state.read;
107
+ }
108
+ /** query workers: reads of SitePage nodes their nodes don't have */
109
+ function sitePageNodeMisses() {
110
+ return state.worker?.misses ?? 0;
111
+ }
112
+ /**
113
+ * Query workers whose nodes have no SitePage nodes (call once the worker started): which pages they
114
+ * leave to the main thread, which builds them once it created the nodes.
115
+ *
116
+ * - A query that read SitePage nodes is left. So is any query that ran meanwhile (queries run
117
+ * concurrently: the read may have been its), and later pages with one of these queries are left
118
+ * without running it (it most likely reads them again) – unless the query ran without a read
119
+ * before (e.g. the template of most pages, running next to the one that reads them). Leaving a
120
+ * page that didn't read them only costs building it later.
121
+ * - When SitePage nodes were read while the worker started (e.g. by createResolvers), every query
122
+ * is left: none of this worker's results can be trusted.
123
+ *
124
+ * Pages without a query read no nodes. Workers whose nodes have SitePage nodes leave none.
125
+ */
126
+ function createSitePageDeferrals() {
127
+ const all = sitePageNodeMisses() > 0;
128
+ /** queries that ran meanwhile reads found none, and never without one */
129
+ const queries = /* @__PURE__ */ new Set();
130
+ /** queries that ran without a read */
131
+ const clean = /* @__PURE__ */ new Set();
132
+ return {
133
+ /** the page's query (index) is not run: the page is left to the main thread */
134
+ skip: (query) => all || queries.has(query),
135
+ /** before a query runs: what `missed` compares with */
136
+ start: () => sitePageNodeMisses(),
137
+ /** after the query ran: whether its page is left to the main thread */
138
+ missed(start, query) {
139
+ if (sitePageNodeMisses() === start) {
140
+ clean.add(query);
141
+ return false;
142
+ }
143
+ if (!clean.has(query)) queries.add(query);
144
+ return true;
145
+ }
146
+ };
147
+ }
148
+ /**
149
+ * Node changes made by creating the SitePage nodes of existing pages, so far: no query that ran
150
+ * before read these nodes (it would have created them), so the node states incremental query
151
+ * running saved before can take them.
152
+ */
153
+ function materializedChanges() {
154
+ return state.materialized;
155
+ }
156
+ /** the page queries depend on SitePage nodes (the next build wants them from the start) */
157
+ function sitePageNodesDependedOn(pages) {
158
+ for (const path in pages) {
159
+ const { n, c } = pages[path];
160
+ if (c.includes("SitePage") || c.includes("*") || n.some((id) => id.startsWith("SitePage "))) {
161
+ state.dependedOn = true;
162
+ return true;
163
+ }
164
+ }
165
+ return false;
166
+ }
167
+ /**
168
+ * The node types with nodes, with SitePage when the pages' SitePage nodes would exist (they are
169
+ * created when read)
170
+ */
171
+ function withSitePageType(types) {
172
+ if (types.includes("SitePage")) return types;
173
+ return (state.worker ? !state.worker.available : !state.created && store.getState().pages.size > 0) ? [...types, "SitePage"] : types;
174
+ }
175
+ /** runs `fn` without reporting the SitePage nodes it reads (goatly's own SitePage code) */
176
+ function withoutSitePageReads(fn) {
177
+ const watcher = getSitePageReadWatcher();
178
+ if (watcher === null) return fn();
179
+ watchSitePageReads(null);
180
+ try {
181
+ return fn();
182
+ } finally {
183
+ watchSitePageReads(watcher);
184
+ }
185
+ }
186
+ /** The SitePage node of a page, like Gatsby's internal-data-bridge creates it. */
187
+ function sitePageNode(page) {
188
+ const { updatedAt: _u, ...nodeData } = page;
189
+ const node = {
190
+ ...nodeData,
191
+ pageContext: page.context,
192
+ id: `${SITE_PAGE_ID_PREFIX}${page.path}`,
193
+ parent: null,
194
+ children: [],
195
+ internal: {
196
+ type: "SitePage",
197
+ contentDigest: ""
198
+ }
199
+ };
200
+ delete node.context;
201
+ node.internal.contentDigest = createContentDigest({
202
+ ...node,
203
+ internal: void 0
204
+ });
205
+ return node;
206
+ }
207
+ /**
208
+ * The actions that create (or touch, when unchanged) the SitePage node of a page created with
209
+ * createPage – none while SitePage nodes aren't created.
210
+ */
211
+ function sitePageNodeActions(page, actionOptions, nextCounter) {
212
+ if (!state.created) return [];
213
+ const node = sitePageNode(page);
214
+ const ds = getDataStore();
215
+ const digest = node.internal.contentDigest;
216
+ const unchanged = typeof ds.getNodeDigest === "function" ? ds.getNodeDigest(node.id) === digest : false;
217
+ const oldNode = unchanged ? void 0 : ds.getNode(node.id);
218
+ if (unchanged || oldNode && oldNode.internal.contentDigest === digest) return [{
219
+ ...actionOptions,
220
+ type: "TOUCH_NODE",
221
+ plugin: PLUGIN,
222
+ payload: node.id
223
+ }];
224
+ node.internal.owner = PLUGIN.name;
225
+ node.internal.counter = nextCounter();
226
+ return [{
227
+ ...actionOptions,
228
+ type: "CREATE_NODE",
229
+ plugin: PLUGIN,
230
+ oldNode,
231
+ payload: node
232
+ }];
233
+ }
234
+ /** deletes the SitePage node of a deleted page */
235
+ function deleteSitePageNode(pagePath) {
236
+ const node = getDataStore().getNode(`${SITE_PAGE_ID_PREFIX}${pagePath}`);
237
+ if (node) store.dispatch({
238
+ type: "DELETE_NODE",
239
+ plugin: PLUGIN,
240
+ payload: node
241
+ });
242
+ }
243
+ /** creates the SitePage nodes of all pages created so far (the first read), in page order */
244
+ function createNodesOfExistingPages(read) {
245
+ state.created = true;
246
+ const { pages } = store.getState();
247
+ if (!pages.size) return;
248
+ const before = getNodeChangeCount();
249
+ const nextCounter = () => store.getState().status.LAST_NODE_COUNTER + 1;
250
+ withoutSitePageReads(() => {
251
+ for (const page of pages.values()) store.dispatch(sitePageNodeActions(page, {}, nextCounter));
252
+ });
253
+ state.materialized += getNodeChangeCount() - before;
254
+ reporter.verbose(`Created the SitePage nodes of ${pages.size} pages (${read})`);
255
+ }
256
+ const recordFile = (cacheDir) => path.join(cacheDir, "data", "site-page-nodes.json");
257
+ /**
258
+ * Whether the build that persisted the nodes read SitePage nodes (or its queries depended on them):
259
+ * then this build creates them from the start.
260
+ */
261
+ function readSitePageRecord(cacheDir) {
262
+ try {
263
+ const record = JSON.parse(fs.readFileSync(recordFile(cacheDir), "utf8"));
264
+ return record?.version === RECORD_VERSION && record.wanted === true;
265
+ } catch {
266
+ return false;
267
+ }
268
+ }
269
+ /** saves whether SitePage nodes are wanted, with the persisted nodes */
270
+ function writeSitePageRecord(cacheDir) {
271
+ writeFileIfChanged(recordFile(cacheDir), JSON.stringify({
272
+ version: RECORD_VERSION,
273
+ wanted: state.read || state.dependedOn
274
+ }));
275
+ }
276
+ watchSitePageReads(onRead);
277
+ export { LAZY_SITE_PAGE_NODES_ENV, createSitePageDeferrals, deleteSitePageNode, materializedChanges, readSitePageNodes, readSitePageRecord, resetSitePageNodes, sitePageNodeActions, sitePageNodeMisses, sitePageNodesCreated, sitePageNodesDependedOn, sitePageNodesWereRead, startSitePageNodes, startWorkerSitePageNodes, withSitePageType, withoutSitePageReads, writeSitePageRecord };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,107 @@
1
+ import { isBun } from "./runtime.js";
2
+ import crypto, { createHash } from "node:crypto";
3
+ import objectHash from "node-object-hash";
4
+ // src/node/utils/content-digest.ts
5
+ const hasher = objectHash({
6
+ coerce: false,
7
+ alg: "md5",
8
+ enc: "hex",
9
+ sort: {
10
+ map: true,
11
+ object: true,
12
+ array: false,
13
+ set: false
14
+ }
15
+ });
16
+ const md5Hex = typeof crypto.hash === "function" ? (s) => crypto.hash("md5", s) : (s) => createHash("md5").update(s).digest("hex");
17
+ const STREAM_MIN_LENGTH = isBun ? 1e400 : 2048;
18
+ /**
19
+ * Appends node-object-hash's string of `v` (with the options of `hasher`) to `out`. Plain objects,
20
+ * arrays and primitives are written here, any other value by node-object-hash itself.
21
+ */
22
+ function write(out, v) {
23
+ switch (typeof v) {
24
+ case "string":
25
+ if (v.length >= STREAM_MIN_LENGTH) {
26
+ out.hash ??= createHash("md5");
27
+ out.hash.update(out.s + "<:s>:");
28
+ out.hash.update(v);
29
+ out.s = "";
30
+ } else out.s += "<:s>:" + v;
31
+ return;
32
+ case "number":
33
+ out.s += "<:n>:" + v;
34
+ return;
35
+ case "boolean":
36
+ out.s += v ? "<:b>:true" : "<:b>:false";
37
+ return;
38
+ case "undefined":
39
+ out.s += "<:undf>";
40
+ return;
41
+ case "object": {
42
+ if (v === null) {
43
+ out.s += "<:null>";
44
+ return;
45
+ }
46
+ if (typeof v.toHashableString === "function") break;
47
+ const ctor = v.constructor;
48
+ if (ctor === Object) {
49
+ const keys = Object.keys(v).sort();
50
+ out.s += "{";
51
+ for (let i = 0; i < keys.length; i++) {
52
+ const key = keys[i];
53
+ out.s += (i === 0 ? "" : ",") + key + ":";
54
+ write(out, v[key]);
55
+ }
56
+ out.s += "}";
57
+ return;
58
+ }
59
+ if (ctor === Array && Array.isArray(v)) {
60
+ out.s += "[";
61
+ for (let i = 0; i < v.length; i++) {
62
+ if (i > 0) out.s += ",";
63
+ const item = v[i];
64
+ if (item !== void 0 || i in v) write(out, item);
65
+ }
66
+ out.s += "]";
67
+ return;
68
+ }
69
+ }
70
+ }
71
+ out.s += hasher.sort(v);
72
+ }
73
+ function createContentDigest(input) {
74
+ if (typeof input === "object" && !Buffer.isBuffer(input)) {
75
+ const out = {
76
+ s: "",
77
+ hash: null
78
+ };
79
+ write(out, input);
80
+ return out.hash === null ? md5Hex(out.s) : out.hash.update(out.s).digest("hex");
81
+ }
82
+ return createHash("md5").update(input).digest("hex");
83
+ }
84
+ /**
85
+ * Gatsby overrides createContentDigest inside node APIs to strip auto-generated
86
+ * fields from nodes, so that digests stay stable.
87
+ */
88
+ function createNodeContentDigest(node) {
89
+ if (!node?.internal?.type) return createContentDigest(node);
90
+ return createContentDigest({
91
+ ...node,
92
+ internal: {
93
+ ...node.internal,
94
+ contentDigest: void 0,
95
+ owner: void 0,
96
+ fieldOwners: void 0,
97
+ ignoreType: void 0,
98
+ counter: void 0
99
+ },
100
+ fields: void 0
101
+ });
102
+ }
103
+ /** Fast non-cryptographic hash for cache keys (not user-facing). */
104
+ function quickHash(input) {
105
+ return createHash("sha1").update(input).digest("base64url").slice(0, 20);
106
+ }
107
+ export { createContentDigest, createNodeContentDigest, quickHash };
@@ -0,0 +1,104 @@
1
+ import { compatEnv } from "./env.js";
2
+ import { findCgroupLevels } from "./memory-signals.js";
3
+ import path from "node:path";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import { execFileSync } from "node:child_process";
7
+ // src/node/utils/cpus.ts
8
+ /**
9
+ * How many CPUs a build may use, which sizes its worker threads. Correct in containers: on Linux
10
+ * the CPU quota of every cgroup level counts (`docker run --cpus=2`, a Kubernetes CPU limit).
11
+ * os.availableParallelism() knows the CPUs the process may run on (its affinity, e.g.
12
+ * `--cpuset-cpus`) and, with cgroup v2, the quota of its own cgroup – not a quota of cgroup v1 (a
13
+ * 1.5-CPU quota there: all 4 CPUs of the machine, Node 22.23), so a container with 2 CPUs' worth
14
+ * of time on a 64-core host could start 16 workers that share them.
15
+ */
16
+ const SYSCTL = "/usr/sbin/sysctl";
17
+ /** the logical CPUs this process may run on (its CPU affinity, where the runtime knows it) */
18
+ function logicalCpus() {
19
+ return Math.max(1, os.availableParallelism?.() ?? os.cpus().length);
20
+ }
21
+ /** the CPUs of a cgroup v2 `cpu.max` ("<quota> <period>" in µs, "max": none), undefined: no quota */
22
+ function parseCpuMax(text) {
23
+ const [quota, period] = text.trim().split(/\s+/).map(Number);
24
+ return quota > 0 && period > 0 ? quota / period : void 0;
25
+ }
26
+ /**
27
+ * The CPU quota (in CPUs, e.g. 1.5) of this process's cgroups, the lowest of every level's:
28
+ * cgroup v2's `cpu.max`, v1's `cpu.cfs_quota_us` / `cpu.cfs_period_us`. undefined: none (or not
29
+ * Linux).
30
+ */
31
+ function cgroupCpuQuota(options = {}) {
32
+ if ((options.platform ?? process.platform) !== "linux") return void 0;
33
+ const read = (file) => {
34
+ try {
35
+ return fs.readFileSync(file, "utf8");
36
+ } catch {
37
+ return;
38
+ }
39
+ };
40
+ const levels = findCgroupLevels(read(path.join(options.procRoot ?? "/proc", "self/cgroup")) ?? "", "cpu", {
41
+ v1: ["cpu.cfs_quota_us", "cpu.cfs_period_us"],
42
+ v2: ["cpu.max"]
43
+ }, options.cgroupRoot);
44
+ let quota;
45
+ for (const { version, dir } of levels) {
46
+ const cpus = version === "v2" ? parseCpuMax(read(path.join(dir, "cpu.max")) ?? "") : parseCpuMax(`${read(path.join(dir, "cpu.cfs_quota_us")) ?? ""} ${read(path.join(dir, "cpu.cfs_period_us")) ?? ""}`);
47
+ if (cpus !== void 0) quota = Math.min(quota ?? 1e400, cpus);
48
+ }
49
+ return quota;
50
+ }
51
+ /** the cores of /proc/cpuinfo (each "physical id" and "core id" once), undefined: not told */
52
+ function parseCpuinfoCores(cpuinfo) {
53
+ const cores = /* @__PURE__ */ new Set();
54
+ for (const block of cpuinfo.split(/\n\s*\n/)) {
55
+ const field = (name) => new RegExp(`^${name}\\s*:\\s*(\\S+)`, "m").exec(block)?.[1];
56
+ const core = field("core id");
57
+ if (core !== void 0) cores.add(`${field("physical id") ?? ""}:${core}`);
58
+ }
59
+ return cores.size > 0 ? cores.size : void 0;
60
+ }
61
+ /**
62
+ * The physical cores (without SMT siblings, as Gatsby counts CPUs by default) – at most the
63
+ * logical CPUs the process may run on. Linux: /proc/cpuinfo, macOS: `sysctl hw.physicalcpu`; where
64
+ * the system doesn't tell (other platforms, some VMs and ARM boards): the logical CPUs.
65
+ */
66
+ function physicalCpus(options = {}) {
67
+ const logical = options.logical ?? logicalCpus();
68
+ const platform = options.platform ?? process.platform;
69
+ let cores;
70
+ try {
71
+ if (platform === "linux") cores = parseCpuinfoCores(fs.readFileSync(path.join(options.procRoot ?? "/proc", "cpuinfo"), "utf8"));
72
+ else if (platform === "darwin") cores = Number(execFileSync(SYSCTL, ["-n", "hw.physicalcpu"], {
73
+ encoding: "utf8",
74
+ timeout: 2e3
75
+ }));
76
+ } catch {}
77
+ return cores !== void 0 && cores >= 1 ? Math.min(logical, Math.floor(cores)) : logical;
78
+ }
79
+ /**
80
+ * The CPUs a build plans its worker threads with:
81
+ * 1. GOATLY_CPU_COUNT (or Gatsby's GATSBY_CPU_COUNT, so a site tuned for Gatsby builds with as
82
+ * many workers here): a number, `logical_cores` or `physical_cores`;
83
+ * 2. else the logical CPUs the process may run on, at most the CPU quota of its cgroups (Linux),
84
+ * rounded down like Node rounds the quota it knows of – at least 1.
85
+ */
86
+ function cpuCount(options = {}) {
87
+ const logical = options.logical ?? logicalCpus();
88
+ const env = options.env ?? process.env;
89
+ const setting = compatEnv("GOATLY_CPU_COUNT", env)?.trim();
90
+ if (setting) {
91
+ if (setting === "logical_cores") return logical;
92
+ if (setting === "physical_cores") return physicalCpus({
93
+ ...options,
94
+ logical
95
+ });
96
+ const count = Number(setting);
97
+ if (Number.isFinite(count) && count >= 1) return Math.floor(count);
98
+ const name = env.GOATLY_CPU_COUNT ? "GOATLY_CPU_COUNT" : "GATSBY_CPU_COUNT";
99
+ options.warn?.(`${name}=${setting} is not a number of CPUs, "logical_cores" or "physical_cores" – ignored`);
100
+ }
101
+ const quota = cgroupCpuQuota(options);
102
+ return quota === void 0 ? logical : Math.max(1, Math.min(logical, Math.floor(quota)));
103
+ }
104
+ export { cgroupCpuQuota, cpuCount, logicalCpus, parseCpuMax, parseCpuinfoCores, physicalCpus };
@@ -0,0 +1,51 @@
1
+ import crypto from "node:crypto";
2
+ // src/node/utils/create-node-id.ts
3
+ /** Same seed constant as Gatsby so that generated node ids are identical. */
4
+ const SEED_CONSTANT = "638f7a53-c567-4eca-8fc1-b23efb1cfb2b";
5
+ const HEX = "0123456789abcdef";
6
+ const sha1Binary = typeof crypto.hash === "function" ? (data) => crypto.hash("sha1", data, "binary") : (data) => crypto.createHash("sha1").update(data).digest("binary");
7
+ const hashInput = Buffer.allocUnsafe(4096);
8
+ const uuidChars = Buffer.alloc(36, "-");
9
+ function uuidToBytes(uuid) {
10
+ return Buffer.from(uuid.replace(/-/g, ""), "hex");
11
+ }
12
+ /** UUID v5 of `name` in the namespace given as its 16 bytes */
13
+ function v5(name, namespace) {
14
+ const size = 16 + name.length * 3;
15
+ const buf = size <= hashInput.length ? hashInput : Buffer.allocUnsafe(size);
16
+ buf.set(namespace);
17
+ const digest = sha1Binary(buf.subarray(0, 16 + buf.write(name, 16)));
18
+ for (let i = 0, j = 0; i < 16; i++) {
19
+ let byte = digest.charCodeAt(i);
20
+ if (i === 6) byte = byte & 15 | 80;
21
+ else if (i === 8) byte = byte & 63 | 128;
22
+ if (j === 8 || j === 13 || j === 18 || j === 23) j++;
23
+ uuidChars[j++] = HEX.charCodeAt(byte >> 4);
24
+ uuidChars[j++] = HEX.charCodeAt(byte & 15);
25
+ }
26
+ return uuidChars.toString("latin1");
27
+ }
28
+ /** RFC 4122 UUID v5 (SHA-1, namespaced) – identical output to the `uuid` package's v5(). */
29
+ function uuidv5(name, namespace) {
30
+ const ns = uuidToBytes(namespace);
31
+ if (ns.length !== 16) throw new TypeError("Invalid UUID");
32
+ return v5(name, ns);
33
+ }
34
+ const SEED_BYTES = uuidToBytes(SEED_CONSTANT);
35
+ const namespaceBytes = /* @__PURE__ */ new Map();
36
+ /**
37
+ * Generate a stable, unique node id. Matches `gatsby/dist/utils/create-node-id`.
38
+ */
39
+ function createNodeId(id, namespace = "") {
40
+ let input = id;
41
+ if (typeof input === "number") input = input.toString();
42
+ else if (typeof input !== "string") throw new Error(`createNodeId() expects a string or number, received ${typeof input}`);
43
+ let ns = namespaceBytes.get(namespace);
44
+ if (ns === void 0) {
45
+ ns = uuidToBytes(v5(namespace, SEED_BYTES));
46
+ namespaceBytes.set(namespace, ns);
47
+ }
48
+ if (input === "" && namespace === "") return v5("", SEED_BYTES);
49
+ return v5(input, ns);
50
+ }
51
+ export { createNodeId, uuidv5 };
@@ -0,0 +1,25 @@
1
+ // src/node/utils/env.ts
2
+ /**
3
+ * Environment variables of Gatsby that goatly supports, by their goatly name, mapped to the Gatsby
4
+ * name that is read as well (so a site moved from Gatsby keeps working unchanged).
5
+ *
6
+ * The mapping goes one way only: the Gatsby names of these options are read, but goatly's own
7
+ * options (`GOATLY_WORKERS`, `GOATLY_HEAP_LIMIT`, …) are never read as `GATSBY_*`.
8
+ */
9
+ const GATSBY_ENV_ALIASES = {
10
+ GOATLY_ACTIVE_ENV: "GATSBY_ACTIVE_ENV",
11
+ GOATLY_CPU_COUNT: "GATSBY_CPU_COUNT",
12
+ GOATLY_VERBOSE: "GATSBY_VERBOSE",
13
+ GOATLY_EXPERIMENTAL_ENABLE_REFRESH: "GATSBY_EXPERIMENTAL_ENABLE_REFRESH",
14
+ ENABLE_GOATLY_REFRESH_ENDPOINT: "ENABLE_GATSBY_REFRESH_ENDPOINT"
15
+ };
16
+ /**
17
+ * The value of an option that Gatsby has too: the goatly name when it is set (and not empty),
18
+ * otherwise the Gatsby name.
19
+ */
20
+ function compatEnv(name, env = process.env) {
21
+ const value = env[name];
22
+ if (value !== void 0 && value !== "") return value;
23
+ return env[GATSBY_ENV_ALIASES[name]];
24
+ }
25
+ export { GATSBY_ENV_ALIASES, compatEnv };
@@ -0,0 +1,74 @@
1
+ import fs from "node:fs";
2
+ // src/node/utils/fs-retry.ts
3
+ /**
4
+ * Retries of file operations that Windows fails transiently (graceful-fs style).
5
+ *
6
+ * On Windows, replacing or removing a file fails with EPERM, EACCES or EBUSY while another
7
+ * handle has it open without delete sharing (antivirus, the search indexer, a reader on a file
8
+ * system without POSIX delete semantics), and a name stays taken ("delete pending") until the last
9
+ * handle of a removed file closes. These go away within a moment, so the operation is retried with
10
+ * backoff for about 1.5 s before the error is thrown. On other platforms it is the plain call.
11
+ */
12
+ /** the errors Windows gives while another handle holds the file */
13
+ const TRANSIENT = /* @__PURE__ */ new Set([
14
+ "EPERM",
15
+ "EACCES",
16
+ "EBUSY"
17
+ ]);
18
+ const DEFAULT_TOTAL_MS = 1500;
19
+ const FIRST_DELAY_MS = 5;
20
+ const MAX_DELAY_MS = 200;
21
+ /** whether `e` is an error a retry can get past */
22
+ const isTransientFsError = (e) => typeof e === "object" && e !== null && TRANSIENT.has(e.code ?? "");
23
+ /** the delays between attempts: doubling, capped, adding up to at most `totalMs` */
24
+ function retryDelays(totalMs = DEFAULT_TOTAL_MS) {
25
+ const delays = [];
26
+ let sum = 0;
27
+ for (let d = FIRST_DELAY_MS; sum + Math.min(d, MAX_DELAY_MS) <= totalMs; d *= 2) {
28
+ delays.push(Math.min(d, MAX_DELAY_MS));
29
+ sum += delays.at(-1);
30
+ }
31
+ return delays;
32
+ }
33
+ const shouldRetry = (options) => (options.platform ?? process.platform) === "win32";
34
+ let sleeper;
35
+ /** blocks the thread (main thread included) for `ms` milliseconds */
36
+ function sleepSync(ms) {
37
+ sleeper ??= new Int32Array(new SharedArrayBuffer(4));
38
+ Atomics.wait(sleeper, 0, 0, ms);
39
+ }
40
+ /** runs `op`, on Windows again after a transient error until about `totalMs` passed */
41
+ function retrySync(op, options = {}) {
42
+ if (!shouldRetry(options)) return op();
43
+ for (const delay of retryDelays(options.totalMs)) {
44
+ try {
45
+ return op();
46
+ } catch (e) {
47
+ if (!isTransientFsError(e)) throw e;
48
+ }
49
+ sleepSync(delay);
50
+ }
51
+ return op();
52
+ }
53
+ /** the async variant of `retrySync` */
54
+ async function retryAsync(op, options = {}) {
55
+ if (!shouldRetry(options)) return op();
56
+ for (const delay of retryDelays(options.totalMs)) {
57
+ try {
58
+ return await op();
59
+ } catch (e) {
60
+ if (!isTransientFsError(e)) throw e;
61
+ }
62
+ await new Promise((resolve) => setTimeout(resolve, delay));
63
+ }
64
+ return op();
65
+ }
66
+ /** `fs.renameSync`, retried on Windows while the target (or source) is held open */
67
+ function renameSync(from, to, options) {
68
+ retrySync(() => fs.renameSync(from, to), options);
69
+ }
70
+ /** `fs.promises.rename`, retried on Windows while the target (or source) is held open */
71
+ function rename(from, to, options) {
72
+ return retryAsync(() => fs.promises.rename(from, to), options);
73
+ }
74
+ export { isTransientFsError, rename, renameSync, retryAsync, retryDelays, retrySync };