goatly 0.1.0 → 0.1.1

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 (158) hide show
  1. package/README.md +853 -1
  2. package/bin/goatly.js +91 -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 +539 -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 +752 -0
  18. package/dist/node/build/memory-governor.js +448 -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 +54 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +536 -0
  24. package/dist/node/build/query-workers.js +832 -0
  25. package/dist/node/build/render-worker.js +131 -0
  26. package/dist/node/build/state.js +24 -0
  27. package/dist/node/build/timing-breakdown.js +155 -0
  28. package/dist/node/build/worker-pool.js +236 -0
  29. package/dist/node/cache-layout.js +99 -0
  30. package/dist/node/cache.js +1430 -0
  31. package/dist/node/compat/chokidar-shim.js +148 -0
  32. package/dist/node/compat/core-utils-lmdb.js +145 -0
  33. package/dist/node/compat/create-node-id-shim.js +1 -0
  34. package/dist/node/compat/module-hooks.js +245 -0
  35. package/dist/node/compat/redux-shim.js +1 -0
  36. package/dist/node/config/index.js +162 -0
  37. package/dist/node/config/not-found-pages.js +95 -0
  38. package/dist/node/datastore/codec.js +144 -0
  39. package/dist/node/datastore/index.js +127 -0
  40. package/dist/node/datastore/logfile/cache.js +89 -0
  41. package/dist/node/datastore/logfile/index.js +1329 -0
  42. package/dist/node/datastore/logfile/record.js +71 -0
  43. package/dist/node/datastore/types.js +1 -0
  44. package/dist/node/develop/express-compat.js +207 -0
  45. package/dist/node/develop/graphiql.js +22 -0
  46. package/dist/node/develop/hydration-report.js +41 -0
  47. package/dist/node/develop/index.js +618 -0
  48. package/dist/node/develop/local-url.js +10 -0
  49. package/dist/node/develop/ssr-runner.js +66 -0
  50. package/dist/node/gql.js +5 -0
  51. package/dist/node/index.js +15 -0
  52. package/dist/node/info.js +270 -0
  53. package/dist/node/internal-plugins/data-bridge.js +196 -0
  54. package/dist/node/internal-plugins/page-creator.js +318 -0
  55. package/dist/node/loader/import-module.js +160 -0
  56. package/dist/node/node-helpers.js +66 -0
  57. package/dist/node/not-found-pages.js +220 -0
  58. package/dist/node/plugins/api-list.js +12 -0
  59. package/dist/node/plugins/load-plugins.js +427 -0
  60. package/dist/node/plugins/resolve-plugin.js +79 -0
  61. package/dist/node/plugins/static-exports.js +64 -0
  62. package/dist/node/query/compile.js +326 -0
  63. package/dist/node/query/dependencies.js +45 -0
  64. package/dist/node/query/execute.js +417 -0
  65. package/dist/node/query/extract.js +372 -0
  66. package/dist/node/query/gql-tada-introspection.js +124 -0
  67. package/dist/node/query/graphql-env.js +231 -0
  68. package/dist/node/query/graphql-runner.js +79 -0
  69. package/dist/node/redux/actions.js +1 -0
  70. package/dist/node/redux/index.js +133 -0
  71. package/dist/node/redux/node-changes.js +128 -0
  72. package/dist/node/redux/reducers.js +193 -0
  73. package/dist/node/redux/state.js +71 -0
  74. package/dist/node/renderer.js +124 -0
  75. package/dist/node/reporter-transports.js +259 -0
  76. package/dist/node/reporter.js +497 -0
  77. package/dist/node/schema/date.js +539 -0
  78. package/dist/node/schema/extensions.js +315 -0
  79. package/dist/node/schema/index.js +542 -0
  80. package/dist/node/schema/infer.js +388 -0
  81. package/dist/node/schema/inline-objects.js +128 -0
  82. package/dist/node/schema/naming.js +20 -0
  83. package/dist/node/schema/node-model.js +207 -0
  84. package/dist/node/schema/query-engine.js +1808 -0
  85. package/dist/node/schema/resolver-kinds.js +7 -0
  86. package/dist/node/schema/resolvers.js +273 -0
  87. package/dist/node/schema/type-builders.js +45 -0
  88. package/dist/node/schema/types.js +241 -0
  89. package/dist/node/serve.js +90 -0
  90. package/dist/node/site-page-nodes.js +277 -0
  91. package/dist/node/types.js +1 -0
  92. package/dist/node/utils/content-digest.js +107 -0
  93. package/dist/node/utils/create-node-id.js +51 -0
  94. package/dist/node/utils/env.js +24 -0
  95. package/dist/node/utils/fs-retry.js +74 -0
  96. package/dist/node/utils/memory-signals.js +410 -0
  97. package/dist/node/utils/memory.js +400 -0
  98. package/dist/node/utils/murmurhash.js +32 -0
  99. package/dist/node/utils/parser.js +33 -0
  100. package/dist/node/utils/partition-hash.js +19 -0
  101. package/dist/node/utils/paths.js +122 -0
  102. package/dist/node/utils/resolver.js +48 -0
  103. package/dist/node/utils/runtime.js +5 -0
  104. package/dist/node/utils/serializable.js +41 -0
  105. package/dist/node/utils/strings.js +41 -0
  106. package/dist/node/vite/config.js +289 -0
  107. package/dist/node/vite/paths.js +12 -0
  108. package/dist/node/vite/plugin-deps.js +232 -0
  109. package/dist/node/vite/plugin.js +281 -0
  110. package/dist/node/vite/react-compiler.js +362 -0
  111. package/dist/node/vite/source-files.js +83 -0
  112. package/dist/node/vite/static-image.js +136 -0
  113. package/dist/node/vite/styled-components.js +73 -0
  114. package/dist/node/vite/transforms.js +299 -0
  115. package/dist/node/wasm-data/host.js +406 -0
  116. package/dist/node/wasm-data/lower.js +406 -0
  117. package/dist/node/wasm-data/runner.js +79 -0
  118. package/dist/node/wasm-data/worker.js +95 -0
  119. package/dist/reporter.js +5 -0
  120. package/dist/runtime/api-runner.js +81 -0
  121. package/dist/runtime/app.js +256 -0
  122. package/dist/runtime/client-entry.js +4 -0
  123. package/dist/runtime/client.js +383 -0
  124. package/dist/runtime/default-html.js +31 -0
  125. package/dist/runtime/head-markup.js +100 -0
  126. package/dist/runtime/head-sync.js +101 -0
  127. package/dist/runtime/head-tags.js +45 -0
  128. package/dist/runtime/hydration-report.js +111 -0
  129. package/dist/runtime/index.js +12 -0
  130. package/dist/runtime/link.js +293 -0
  131. package/dist/runtime/loader.js +449 -0
  132. package/dist/runtime/not-found.js +61 -0
  133. package/dist/runtime/page-renderer.js +35 -0
  134. package/dist/runtime/preamble.js +47 -0
  135. package/dist/runtime/react-compat.js +14 -0
  136. package/dist/runtime/renderer-shared.js +10 -0
  137. package/dist/runtime/renderers/react-client.js +14 -0
  138. package/dist/runtime/renderers/react-server.js +99 -0
  139. package/dist/runtime/renderers/react.js +17 -0
  140. package/dist/runtime/renderers/types.js +1 -0
  141. package/dist/runtime/root-error-handlers.js +29 -0
  142. package/dist/runtime/router/history.js +132 -0
  143. package/dist/runtime/router/index.js +240 -0
  144. package/dist/runtime/router/utils.js +118 -0
  145. package/dist/runtime/script.js +110 -0
  146. package/dist/runtime/scroll.js +40 -0
  147. package/dist/runtime/slice.js +11 -0
  148. package/dist/runtime/ssr.js +240 -0
  149. package/dist/runtime/static-query.js +47 -0
  150. package/dist/utils.js +4 -0
  151. package/package.json +105 -3
  152. package/types/graphql-tada.d.ts +223 -0
  153. package/types/graphql.d.ts +2 -0
  154. package/types/index.d.ts +2287 -0
  155. package/types/node.d.ts +380 -0
  156. package/types/reporter.d.ts +187 -0
  157. package/types/router.d.ts +102 -0
  158. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,539 @@
1
+ import { compatEnv } from "./utils/env.js";
2
+ import { apiRunnerNode, waitForCascade } from "./api-runner.js";
3
+ import { closeCaches, commitCacheRun, getCache, mergeCacheRuns, openPluginCache, setCacheRoot, setCacheRun, startCacheRun } from "./cache.js";
4
+ import { releaseCoreUtilsMutexes } from "./compat/core-utils-lmdb.js";
5
+ import { LogFileDataStore } from "./datastore/logfile/index.js";
6
+ import { PLUGIN_CACHE_DIR, writeFileIfChanged } from "./cache-layout.js";
7
+ import { getChangedNodeTypes } from "./redux/node-changes.js";
8
+ import { loadConfigFile, normalizeConfig, readSitePackageJson, reportIgnoredConfig } from "./config/index.js";
9
+ import { getDataStore, getNode, setDataStore } from "./datastore/index.js";
10
+ import { createDataBridgePlugin, createProd404Plugin } from "./internal-plugins/data-bridge.js";
11
+ import { createPageCreatorPlugin } from "./internal-plugins/page-creator.js";
12
+ import { reportNotFoundPages } from "./not-found-pages.js";
13
+ import { loadPlugins } from "./plugins/load-plugins.js";
14
+ import { extractAndCompileQueries } from "./query/compile.js";
15
+ import { graphqlForApis } from "./query/graphql-runner.js";
16
+ import { emitter, store } from "./redux/index.js";
17
+ import reporter from "./reporter.js";
18
+ import { buildSchema, getInferenceMetadata, setInferenceBaseline, setInferenceSnapshot } from "./schema/index.js";
19
+ import { clearQueryEngineCaches } from "./schema/query-engine.js";
20
+ import { deleteNode } from "./actions/index.js";
21
+ import { pruneCompletedJobs } from "./actions/job-store.js";
22
+ import { sitePageNodesCreated, startSitePageNodes, startWorkerSitePageNodes, withoutSitePageReads, writeSitePageRecord } from "./site-page-nodes.js";
23
+ import { registerGatsbyModuleHooks } from "./compat/module-hooks.js";
24
+ import { useRenderer } from "./renderer.js";
25
+ import { createContentDigest } from "./utils/content-digest.js";
26
+ import { TEMP_MODULE, resolveApiFile } from "./loader/import-module.js";
27
+ import { runtimeName } from "./utils/runtime.js";
28
+ import { isMainThread } from "node:worker_threads";
29
+ import path from "node:path";
30
+ import fs from "node:fs";
31
+ import v8 from "node:v8";
32
+ // src/node/bootstrap.ts
33
+ const GOATLY_VERSION = "0.1.1";
34
+ const DEFAULT_EXTENSIONS = [
35
+ ".mjs",
36
+ ".js",
37
+ ".jsx",
38
+ ".wasm",
39
+ ".json",
40
+ ".tsx",
41
+ ".ts"
42
+ ];
43
+ async function loadEnvFiles(directory, command) {
44
+ const mode = compatEnv("GOATLY_ACTIVE_ENV") || process.env.NODE_ENV || (command === "build" ? "production" : "development");
45
+ const { loadEnv } = await import("vite");
46
+ const env = loadEnv(mode, directory, "");
47
+ for (const [key, value] of Object.entries(env)) if (process.env[key] === void 0) process.env[key] = value;
48
+ }
49
+ /** whether the nodes of the previous build were restored from the cache (main thread) */
50
+ let datastoreRestored = false;
51
+ /**
52
+ * Marker of the restored nodes: written after a completed build persisted them (and stored in its
53
+ * query state), removed as soon as a process may change them – incremental builds only trust
54
+ * node changes recorded relative to nodes they know (develop or a failed build may have changed
55
+ * the store, e.g. the sqlite store writes in place).
56
+ */
57
+ let restoredGeneration;
58
+ /**
59
+ * Whether public/ was missing or empty when the run started (main thread): the build state then
60
+ * does not describe what is in public/, whatever is left of it in .cache.
61
+ */
62
+ let publicDirWasMissing = false;
63
+ const generationFile = (cacheDir) => path.join(cacheDir, "data", "nodes-generation");
64
+ /** inference results of the persisted nodes (types are only scanned again when they changed) */
65
+ const inferenceStateFile = (cacheDir) => path.join(cacheDir, "data", "inference-state.v8");
66
+ const INFERENCE_STATE_VERSION = 1;
67
+ function computeCacheKey(directory, pluginKeys) {
68
+ const { flattenedPlugins, config } = store.getState();
69
+ const files = [];
70
+ for (const base of ["gatsby-config", "gatsby-node"]) {
71
+ const f = resolveApiFile(directory, base);
72
+ if (f) files.push(fs.readFileSync(f, "utf8"));
73
+ }
74
+ for (const name of [
75
+ "package.json",
76
+ "pnpm-lock.yaml",
77
+ "package-lock.json",
78
+ "yarn.lock",
79
+ "bun.lock"
80
+ ]) try {
81
+ files.push(fs.readFileSync(path.join(directory, name), "utf8"));
82
+ } catch {}
83
+ for (const p of flattenedPlugins) {
84
+ if (!p.resolve || p.resolve.includes("node_modules") || !path.isAbsolute(p.resolve)) continue;
85
+ if (p.name === "default-site-plugin" || path.resolve(p.resolve) === path.resolve(directory)) continue;
86
+ files.push(...readPluginFiles(p.resolve));
87
+ }
88
+ return createContentDigest({
89
+ version: GOATLY_VERSION,
90
+ runtime: runtimeName.split(".")[0],
91
+ plugins: pluginKeys,
92
+ trailingSlash: config.trailingSlash,
93
+ files
94
+ });
95
+ }
96
+ /** contents of a local plugin's source files (bounded: 2,000 files of up to 2 MB) */
97
+ function readPluginFiles(dir) {
98
+ const out = [];
99
+ const walk = (current) => {
100
+ let entries;
101
+ try {
102
+ entries = fs.readdirSync(current, { withFileTypes: true });
103
+ } catch {
104
+ return;
105
+ }
106
+ entries.sort((a, b) => a.name.localeCompare(b.name));
107
+ for (const entry of entries) {
108
+ if (out.length >= 2e3) return;
109
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || TEMP_MODULE.test(entry.name)) continue;
110
+ const full = path.join(current, entry.name);
111
+ if (entry.isDirectory()) walk(full);
112
+ else if (entry.isFile()) try {
113
+ if (fs.statSync(full).size <= 2097152) out.push(`${path.relative(dir, full)}\0${fs.readFileSync(full, "utf8")}`);
114
+ } catch {}
115
+ }
116
+ };
117
+ if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) walk(dir);
118
+ return out;
119
+ }
120
+ function safeJson(v) {
121
+ try {
122
+ return JSON.stringify(v, (_k, val) => typeof val === "function" ? String(val) : val instanceof RegExp ? String(val) : val);
123
+ } catch {
124
+ return "";
125
+ }
126
+ }
127
+ function findRootAncestor(node) {
128
+ let current = node;
129
+ const seen = /* @__PURE__ */ new Set();
130
+ while (current.parent && !seen.has(current.id)) {
131
+ seen.add(current.id);
132
+ const parent = getNode(current.parent);
133
+ if (!parent) break;
134
+ current = parent;
135
+ }
136
+ return current;
137
+ }
138
+ /**
139
+ * Deletes nodes whose root ancestor was not created/touched during sourcing (Gatsby semantics).
140
+ * Stores with type and parent indexes (lazy stores) are checked without loading every node, and
141
+ * stores that know the nodes' owners skip the nodes of stateful source plugins without loading
142
+ * them.
143
+ */
144
+ function deleteStaleNodes() {
145
+ const { nodesTouched, statefulSourcePlugins } = store.getState();
146
+ const ds = getDataStore();
147
+ const stale = [];
148
+ const isStateful = (node) => !!node && statefulSourcePlugins.has(node.internal.owner ?? "");
149
+ /** true when the store knows the node's owner and it is stateful (nothing is read) */
150
+ const ownerIsStateful = (id) => {
151
+ const owner = statefulSourcePlugins.size ? ds.getNodeOwner?.(id) : void 0;
152
+ return owner !== void 0 && statefulSourcePlugins.has(owner);
153
+ };
154
+ if (typeof ds.getNodeIdsByType === "function" && typeof ds.getNodeParent === "function") {
155
+ const rootIdOf = (id) => {
156
+ const seen = /* @__PURE__ */ new Set();
157
+ let current = id;
158
+ for (;;) {
159
+ seen.add(current);
160
+ const parent = ds.getNodeParent(current);
161
+ if (!parent || seen.has(parent) || ds.getNodeType?.(parent) === void 0) return current;
162
+ current = parent;
163
+ }
164
+ };
165
+ for (const type of ds.getTypes()) {
166
+ if (type === "SitePage") continue;
167
+ for (const id of ds.getNodeIdsByType(type)) {
168
+ const rootId = rootIdOf(id);
169
+ if (nodesTouched.has(rootId)) continue;
170
+ if (ownerIsStateful(id) || rootId !== id && ownerIsStateful(rootId)) continue;
171
+ const node = getNode(id);
172
+ if (!node || isStateful(node) || isStateful(getNode(rootId))) continue;
173
+ stale.push(node);
174
+ }
175
+ }
176
+ } else for (const node of ds.iterateNodes()) {
177
+ if (node.internal.type === "SitePage" || isStateful(node)) continue;
178
+ const root = findRootAncestor(node);
179
+ if (!nodesTouched.has(root.id) && !isStateful(root)) stale.push(node);
180
+ }
181
+ for (const node of stale) if (getNode(node.id)) deleteNode(node, { name: node.internal.owner ?? "internal" });
182
+ if (stale.length) reporter.verbose(`Deleted ${stale.length} stale nodes`);
183
+ }
184
+ /**
185
+ * SitePage nodes of pages that were not created again (unchanged pages keep their node) – all of
186
+ * them while SitePage nodes aren't created (the persisted nodes of a build that read them).
187
+ */
188
+ function deleteOrphanSitePages() {
189
+ const { pages } = store.getState();
190
+ const ds = getDataStore();
191
+ const ids = typeof ds.getNodeIdsByType === "function" ? ds.getNodeIdsByType("SitePage") : [...ds.iterateNodesByType("SitePage")].map((n) => n.id);
192
+ const created = sitePageNodesCreated();
193
+ let deleted = 0;
194
+ withoutSitePageReads(() => {
195
+ for (const id of ids) {
196
+ if (created && id.startsWith("SitePage ") && pages.has(id.slice(9))) continue;
197
+ deleteNode(id, { name: "internal-data-bridge" });
198
+ deleted++;
199
+ }
200
+ });
201
+ if (deleted) reporter.verbose(created ? `Deleted ${deleted} SitePage nodes of removed pages` : `Deleted ${deleted} SitePage nodes: the previous build did not read them`);
202
+ }
203
+ /** Deletes the plugin caches (`cache`, `getCache`) and the given other entries of `.cache`. */
204
+ function deleteCaches(cacheDir, other = []) {
205
+ closeCaches();
206
+ for (const sub of [
207
+ ...other,
208
+ "caches",
209
+ PLUGIN_CACHE_DIR
210
+ ]) fs.rmSync(path.join(cacheDir, sub), {
211
+ recursive: true,
212
+ force: true
213
+ });
214
+ setCacheRoot(cacheDir);
215
+ startCacheRun();
216
+ }
217
+ /** Whether `dir` has no entries; also when it is missing or not a readable directory. */
218
+ function isMissingOrEmpty(dir) {
219
+ let handle;
220
+ try {
221
+ handle = fs.opendirSync(dir);
222
+ return handle.readSync() === null;
223
+ } catch {
224
+ return true;
225
+ } finally {
226
+ handle?.closeSync();
227
+ }
228
+ }
229
+ async function initDataStore(config, cacheDir) {
230
+ let ds;
231
+ if (typeof config.datastore === "function") ds = await config.datastore({ cacheDir });
232
+ else if (config.datastore) ds = config.datastore;
233
+ else ds = new LogFileDataStore({ cacheDir });
234
+ setDataStore(ds);
235
+ return ds;
236
+ }
237
+ async function loadSiteAndPlugins(directory, options, dirs, renderer) {
238
+ const { cacheDir, publicDir } = dirs;
239
+ let activity = reporter.activityTimer("load gatsby config");
240
+ activity.start();
241
+ const { config: rawConfig } = await loadConfigFile(directory);
242
+ const config = normalizeConfig(typeof rawConfig === "function" ? await rawConfig({}) : rawConfig);
243
+ try {
244
+ await useRenderer(renderer === void 0 ? config.renderer : renderer ?? void 0, directory);
245
+ } catch (e) {
246
+ reporter.panic(e.message, e);
247
+ }
248
+ if (config.reporter && isMainThread && reporter.transportSource !== "api") reporter.setTransports(config.reporter, "config");
249
+ reportIgnoredConfig(config);
250
+ const sitePackageJson = readSitePackageJson(directory);
251
+ store.dispatch({
252
+ type: "SET_PROGRAM",
253
+ payload: {
254
+ directory,
255
+ command: options.command,
256
+ sitePackageJson,
257
+ prefixPaths: options.command !== "develop" && (!!options.prefixPaths || process.env.PREFIX_PATHS === "true"),
258
+ host: options.host ?? "localhost",
259
+ port: options.port ?? 8e3,
260
+ verbose: !!options.verbose,
261
+ extensions: DEFAULT_EXTENSIONS,
262
+ browserslist: [],
263
+ publicDir,
264
+ cacheDir
265
+ }
266
+ });
267
+ activity.end();
268
+ activity = reporter.activityTimer("load plugins");
269
+ activity.start();
270
+ const flattenedPlugins = await loadPlugins({
271
+ rootDir: directory,
272
+ plugins: config.plugins,
273
+ siteMetadata: config.siteMetadata,
274
+ internalPluginsBefore: [createDataBridgePlugin(), createProd404Plugin()],
275
+ createPageCreator: (opts) => createPageCreatorPlugin(opts)
276
+ });
277
+ store.dispatch({
278
+ type: "SET_SITE_CONFIG",
279
+ payload: { ...config }
280
+ });
281
+ store.dispatch({
282
+ type: "SET_SITE_FLATTENED_PLUGINS",
283
+ payload: flattenedPlugins
284
+ });
285
+ activity.end();
286
+ const extraExtensions = (await apiRunnerNode("resolvableExtensions", { traceId: "initial-resolvableExtensions" })).flat();
287
+ store.dispatch({
288
+ type: "SET_PROGRAM",
289
+ payload: { extensions: [.../* @__PURE__ */ new Set([...DEFAULT_EXTENSIONS, ...extraExtensions.filter((e) => typeof e === "string")])] }
290
+ });
291
+ return { config };
292
+ }
293
+ /**
294
+ * Runs Gatsby's bootstrap sequence:
295
+ * config → plugins → onPreInit → cache → onPluginInit → onPreBootstrap →
296
+ * createSchemaCustomization → sourceNodes → schema (setFieldsOnGraphQLNodeType, createResolvers) →
297
+ * createPages → createPagesStatefully → query extraction → onPostBootstrap.
298
+ */
299
+ async function bootstrap(options) {
300
+ const directory = path.resolve(options.directory);
301
+ const cacheDir = path.join(directory, ".cache");
302
+ const publicDir = path.join(directory, "public");
303
+ const metaFile = path.join(cacheDir, "goatly-cache.json");
304
+ const publicDirMissing = isMissingOrEmpty(publicDir);
305
+ publicDirWasMissing = publicDirMissing;
306
+ const pluginCacheExisted = ["caches", PLUGIN_CACHE_DIR].some((sub) => fs.existsSync(path.join(cacheDir, sub)));
307
+ const cacheIncomplete = publicDirMissing && (pluginCacheExisted || fs.existsSync(metaFile));
308
+ if (process.cwd() !== directory) process.chdir(directory);
309
+ if (options.verbose) reporter.setVerbose(true);
310
+ reporter.isBuild = options.command === "build";
311
+ await loadEnvFiles(directory, options.command);
312
+ registerGatsbyModuleHooks({ build: options.command === "build" });
313
+ fs.mkdirSync(cacheDir, { recursive: true });
314
+ setCacheRoot(cacheDir);
315
+ releaseCoreUtilsMutexes(cacheDir);
316
+ const reverted = startCacheRun();
317
+ let activity;
318
+ const { config } = await loadSiteAndPlugins(directory, options, {
319
+ cacheDir,
320
+ publicDir
321
+ });
322
+ if (reverted) {
323
+ const entries = reverted === 1 ? "entry" : "entries";
324
+ reporter.info(`Reverted ${reverted} plugin cache ${entries} written after the last run that saved its nodes`);
325
+ }
326
+ const pluginKeys = store.getState().flattenedPlugins.map((p) => `${p.name}@${p.version}:${safeJson(p.pluginOptions)}`);
327
+ await apiRunnerNode("onPreInit", {});
328
+ activity = reporter.activityTimer("initialize cache");
329
+ activity.start();
330
+ const cacheKey = computeCacheKey(directory, pluginKeys);
331
+ let previousKey;
332
+ try {
333
+ previousKey = JSON.parse(fs.readFileSync(metaFile, "utf8")).cacheKey;
334
+ } catch {}
335
+ const keyChanged = !!previousKey && previousKey !== cacheKey;
336
+ if (keyChanged) reporter.info("We've detected changes to plugins, config or gatsby-node – deleting the cache");
337
+ if (cacheIncomplete) reporter.info("We've detected an incomplete cache (public is missing or empty) – deleting the cache");
338
+ if (keyChanged || cacheIncomplete) deleteCaches(cacheDir, ["data"]);
339
+ const cacheDeleted = keyChanged || cacheIncomplete;
340
+ fs.mkdirSync(path.join(publicDir, "static"), { recursive: true });
341
+ const ds = await initDataStore(config, cacheDir);
342
+ if (!ds.load && pluginCacheExisted && !cacheDeleted) reporter.warn(`The datastore${ds.name ? ` "${ds.name}"` : ""} does not restore nodes (no load()), but the plugin caches of an earlier run are kept: source plugins that keep a sync token in their cache can miss content in this run. Use a datastore that restores its nodes (the default logfile store or SQLite) or run \`gatsby clean\` before each run.`);
343
+ const cacheRestored = previousKey === cacheKey && !cacheDeleted && ds.load ? await ds.load() : false;
344
+ if (!cacheRestored && ds.load && pluginCacheExisted && !cacheDeleted) {
345
+ reporter.info("No nodes were restored from the cache – deleting the plugin caches");
346
+ deleteCaches(cacheDir);
347
+ }
348
+ clearQueryEngineCaches();
349
+ datastoreRestored = cacheRestored;
350
+ restoredGeneration = void 0;
351
+ if (cacheRestored) {
352
+ try {
353
+ restoredGeneration = fs.readFileSync(generationFile(cacheDir), "utf8").trim() || void 0;
354
+ } catch {}
355
+ let max = 0;
356
+ if (typeof ds.getMaxNodeCounter === "function") max = ds.getMaxNodeCounter();
357
+ else for (const n of ds.iterateNodes()) if ((n.internal.counter ?? 0) > max) max = n.internal.counter ?? 0;
358
+ store.getState().status.LAST_NODE_COUNTER = max;
359
+ reporter.verbose(`Restored ${ds.countNodes()} nodes from cache`);
360
+ }
361
+ startSitePageNodes({
362
+ cacheDir,
363
+ restored: cacheRestored
364
+ });
365
+ fs.rmSync(generationFile(cacheDir), { force: true });
366
+ setInferenceBaseline(restoredGeneration ? readInferenceState(cacheDir) : void 0);
367
+ writeFileIfChanged(metaFile, JSON.stringify({
368
+ cacheKey,
369
+ version: GOATLY_VERSION
370
+ }));
371
+ fs.rmSync(path.join(cacheDir, "fragments"), {
372
+ recursive: true,
373
+ force: true
374
+ });
375
+ fs.mkdirSync(path.join(cacheDir, "fragments"), { recursive: true });
376
+ const prunedJobs = await pruneCompletedJobs();
377
+ if (prunedJobs) reporter.verbose(`Deleted ${prunedJobs} completed job(s) whose files are gone`);
378
+ activity.end();
379
+ await apiRunnerNode("onPluginInit", {});
380
+ await apiRunnerNode("onPreBootstrap", {});
381
+ store.getState().nodesTouched.clear();
382
+ activity = reporter.activityTimer("createSchemaCustomization");
383
+ activity.start();
384
+ await apiRunnerNode("createSchemaCustomization", { traceId: "initial-createSchemaCustomization" });
385
+ activity.end();
386
+ activity = reporter.activityTimer("source and transform nodes");
387
+ activity.start();
388
+ await apiRunnerNode("sourceNodes", {
389
+ traceId: "initial-sourceNodes",
390
+ waitForCascadingActions: true,
391
+ webhookBody: {}
392
+ });
393
+ await waitForCascade("initial-sourceNodes");
394
+ deleteStaleNodes();
395
+ activity.setStatus(`${ds.countNodes()} nodes`);
396
+ activity.end();
397
+ activity = reporter.activityTimer("building schema");
398
+ activity.start();
399
+ await buildSchema();
400
+ activity.end();
401
+ let queries = {
402
+ pageQueries: /* @__PURE__ */ new Map(),
403
+ staticQueries: /* @__PURE__ */ new Map(),
404
+ staticQueriesByFile: /* @__PURE__ */ new Map(),
405
+ fragments: /* @__PURE__ */ new Map(),
406
+ queries: /* @__PURE__ */ new Map(),
407
+ usesGraphqlTypes: false,
408
+ errors: 0
409
+ };
410
+ if (!options.skipPages) {
411
+ activity = reporter.activityTimer("createPages");
412
+ activity.start();
413
+ await apiRunnerNode("createPages", {
414
+ graphql: graphqlForApis,
415
+ traceId: "initial-createPages",
416
+ waitForCascadingActions: true
417
+ });
418
+ await waitForCascade("initial-createPages");
419
+ activity.end();
420
+ activity = reporter.activityTimer("createPagesStatefully");
421
+ activity.start();
422
+ await apiRunnerNode("createPagesStatefully", {
423
+ graphql: graphqlForApis,
424
+ traceId: "initial-createPagesStatefully",
425
+ waitForCascadingActions: true
426
+ });
427
+ await waitForCascade("initial-createPagesStatefully");
428
+ await waitForCascade();
429
+ deleteOrphanSitePages();
430
+ activity.setStatus(`${store.getState().pages.size} pages`);
431
+ activity.end();
432
+ reportNotFoundPages();
433
+ activity = reporter.activityTimer("extract queries from components");
434
+ activity.start();
435
+ queries = await extractAndCompileQueries();
436
+ activity.end();
437
+ }
438
+ await apiRunnerNode("onPostBootstrap", {});
439
+ store.dispatch({
440
+ type: "BOOTSTRAP_FINISHED",
441
+ payload: {}
442
+ });
443
+ reporter.info(`bootstrap finished - ${runtimeName}`);
444
+ return {
445
+ queries,
446
+ cacheRestored
447
+ };
448
+ }
449
+ /**
450
+ * Bootstrap for query workers (parallel query running): loads config & plugins, restores nodes
451
+ * from the datastore snapshot written by the main process, runs `onPluginInit` and rebuilds the
452
+ * schema (createSchemaCustomization, setFieldsOnGraphQLNodeType, createResolvers).
453
+ */
454
+ async function bootstrapWorker(options) {
455
+ const directory = path.resolve(options.directory);
456
+ reporter.isBuild = true;
457
+ registerGatsbyModuleHooks({ build: true });
458
+ const cacheDir = path.join(directory, ".cache");
459
+ const publicDir = path.join(directory, "public");
460
+ setCacheRoot(cacheDir);
461
+ const pluginCache = openPluginCache();
462
+ if (!pluginCache.shared) throw new Error(`query worker: could not open the plugin cache: ${pluginCache.error}`);
463
+ setCacheRun(options.cacheRun);
464
+ const quiet = reporter.silent;
465
+ reporter.silent = true;
466
+ try {
467
+ const { config } = await loadSiteAndPlugins(directory, {
468
+ command: "build",
469
+ prefixPaths: options.prefixPaths
470
+ }, {
471
+ cacheDir,
472
+ publicDir
473
+ }, options.renderer);
474
+ const ds = await initDataStore(config, cacheDir);
475
+ if (!ds.load || !await ds.load()) throw new Error("query worker: could not load the node snapshot");
476
+ startWorkerSitePageNodes({ available: options.sitePageNodes !== false });
477
+ clearQueryEngineCaches();
478
+ await apiRunnerNode("onPluginInit", {});
479
+ await apiRunnerNode("createSchemaCustomization", { traceId: "initial-createSchemaCustomization" });
480
+ let snapshot;
481
+ try {
482
+ if (options.inferenceFile) snapshot = v8.deserialize(fs.readFileSync(options.inferenceFile));
483
+ } catch {}
484
+ setInferenceSnapshot(snapshot);
485
+ try {
486
+ await buildSchema();
487
+ } finally {
488
+ setInferenceSnapshot(void 0);
489
+ }
490
+ } finally {
491
+ reporter.silent = quiet;
492
+ }
493
+ }
494
+ /**
495
+ * Persists plugin caches and nodes, and makes the run's plugin cache writes permanent with the
496
+ * nodes. `generation`: the marker of a completed build (see `restoredGeneration`), written once the
497
+ * nodes are on disk.
498
+ */
499
+ async function persistState(generation) {
500
+ const { cacheDir } = store.getState().program;
501
+ if (!generation && cacheDir) {
502
+ fs.rmSync(generationFile(cacheDir), { force: true });
503
+ fs.rmSync(inferenceStateFile(cacheDir), { force: true });
504
+ }
505
+ await commitCacheRun(() => getDataStore().persist?.());
506
+ mergeCacheRuns();
507
+ if (cacheDir) writeSitePageRecord(cacheDir);
508
+ if (generation) {
509
+ fs.mkdirSync(path.join(cacheDir, "data"), { recursive: true });
510
+ writeInferenceState(cacheDir);
511
+ fs.writeFileSync(generationFile(cacheDir), generation);
512
+ }
513
+ }
514
+ /**
515
+ * Read only with a restored marker. Written before the marker and removed with it (the marker is
516
+ * removed when a run starts): it belongs to the nodes the marker vouches for. (Without the
517
+ * generation, which would change the file with every build.)
518
+ */
519
+ function readInferenceState(cacheDir) {
520
+ try {
521
+ const state = v8.deserialize(fs.readFileSync(inferenceStateFile(cacheDir)));
522
+ if (state?.version === INFERENCE_STATE_VERSION) return state.metadata;
523
+ } catch {}
524
+ }
525
+ function writeInferenceState(cacheDir) {
526
+ const file = inferenceStateFile(cacheDir);
527
+ const metadata = getInferenceMetadata();
528
+ if (!metadata) {
529
+ fs.rmSync(file, { force: true });
530
+ return;
531
+ }
532
+ const changed = getChangedNodeTypes();
533
+ const valid = new Map([...metadata].filter(([type]) => !changed.has(type)));
534
+ writeFileIfChanged(file, v8.serialize({
535
+ version: INFERENCE_STATE_VERSION,
536
+ metadata: valid
537
+ }));
538
+ }
539
+ export { bootstrap, bootstrapWorker, datastoreRestored, deleteStaleNodes, emitter, getCache, persistState, publicDirWasMissing, restoredGeneration };
@@ -0,0 +1,110 @@
1
+ import { slash } from "../utils/paths.js";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ // src/node/build/assets.ts
5
+ function readManifest(publicDir) {
6
+ const file = path.join(publicDir, ".vite", "manifest.json");
7
+ return JSON.parse(fs.readFileSync(file, "utf8"));
8
+ }
9
+ /**
10
+ * The manifest without its keys (source paths, relative to the project root, so for modules
11
+ * outside it, like goatly's client entry, they depend on where the project is): its chunks
12
+ * by output file (content-hashed), with what they import as output files too. What the build hash
13
+ * is computed from, so that the same output gives the same hash wherever the site is built (on
14
+ * Windows the paths across drives differ even more, e.g. a temp dir on C: and the package on D:).
15
+ */
16
+ function manifestFingerprint(manifest) {
17
+ const file = (key) => manifest[key]?.file ?? key;
18
+ return `[${Object.values(manifest).map((c) => JSON.stringify({
19
+ file: c.file,
20
+ name: c.name,
21
+ isEntry: c.isEntry,
22
+ isDynamicEntry: c.isDynamicEntry,
23
+ imports: c.imports?.map(file),
24
+ dynamicImports: c.dynamicImports?.map(file),
25
+ css: c.css,
26
+ assets: c.assets
27
+ })).sort().join(",")}]`;
28
+ }
29
+ /** entries of AssetResolver's cache (MDX pages have a component path each: bounded) */
30
+ const CACHE_ENTRIES = 1e3;
31
+ /** Resolves script/modulepreload/stylesheet URLs for page component chunks from the Vite manifest. */
32
+ var AssetResolver = class {
33
+ manifest;
34
+ root;
35
+ base;
36
+ cache = /* @__PURE__ */ new Map();
37
+ entryKey;
38
+ constructor(manifest, root, base) {
39
+ this.manifest = manifest;
40
+ this.root = root;
41
+ this.base = base;
42
+ this.entryKey = Object.keys(manifest).find((k) => manifest[k].isEntry) ?? "";
43
+ if (!this.entryKey) throw new Error("Client entry not found in the Vite manifest");
44
+ }
45
+ url(file) {
46
+ return `${this.base}${file}`;
47
+ }
48
+ collect(key, js, css, seen) {
49
+ if (seen.has(key)) return;
50
+ seen.add(key);
51
+ const chunk = this.manifest[key];
52
+ if (!chunk) return;
53
+ js.add(chunk.file);
54
+ for (const c of chunk.css ?? []) css.add(c);
55
+ for (const k of chunk.imports ?? []) this.collect(k, js, css, seen);
56
+ }
57
+ keyFor(componentPath) {
58
+ const rel = slash(path.relative(this.root, componentPath));
59
+ if (this.manifest[rel]) return rel;
60
+ const base = rel.split("?")[0];
61
+ if (this.manifest[base]) return base;
62
+ return Object.keys(this.manifest).find((k) => this.manifest[k].src === rel || this.manifest[k].src === base);
63
+ }
64
+ forComponents(componentPaths) {
65
+ const cacheKey = componentPaths.join("|");
66
+ const cached = this.cache.get(cacheKey);
67
+ if (cached) return cached;
68
+ const entryJs = /* @__PURE__ */ new Set();
69
+ const css = /* @__PURE__ */ new Set();
70
+ const seen = /* @__PURE__ */ new Set();
71
+ this.collect(this.entryKey, entryJs, css, seen);
72
+ const pageJs = /* @__PURE__ */ new Set();
73
+ for (const c of componentPaths) {
74
+ const key = this.keyFor(c);
75
+ if (key) this.collect(key, pageJs, css, seen);
76
+ }
77
+ const entryFile = this.manifest[this.entryKey].file;
78
+ const preloads = [...entryJs, ...pageJs].filter((f) => f !== entryFile);
79
+ const assets = {
80
+ scripts: [this.url(entryFile)],
81
+ modulePreloads: preloads.map((f) => this.url(f)),
82
+ stylesheets: [...css].map((f) => this.url(f))
83
+ };
84
+ if (this.cache.size >= CACHE_ENTRIES) this.cache.clear();
85
+ this.cache.set(cacheKey, assets);
86
+ return assets;
87
+ }
88
+ /**
89
+ * Gatsby's chunk-map.json: the JS and CSS files each page component needs beyond the client entry,
90
+ * by component chunk name. The client prefetches them (`<link rel=prefetch>`) for visible links,
91
+ * without running page code.
92
+ */
93
+ chunkMap(components) {
94
+ const entryJs = /* @__PURE__ */ new Set();
95
+ const entryCss = /* @__PURE__ */ new Set();
96
+ const seen = /* @__PURE__ */ new Set();
97
+ this.collect(this.entryKey, entryJs, entryCss, seen);
98
+ const map = {};
99
+ for (const [chunkName, componentPath] of components) {
100
+ const key = this.keyFor(componentPath);
101
+ if (!key) continue;
102
+ const js = /* @__PURE__ */ new Set();
103
+ const css = /* @__PURE__ */ new Set();
104
+ this.collect(key, js, css, new Set(seen));
105
+ map[chunkName] = [...js, ...[...css].filter((c) => !entryCss.has(c))].map((f) => this.url(f));
106
+ }
107
+ return map;
108
+ }
109
+ };
110
+ export { AssetResolver, manifestFingerprint, readManifest };