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,618 @@
1
+ import { bootstrap, persistState } from "../bootstrap.js";
2
+ import { finishCaches } from "../cache.js";
3
+ import { apiRunnerNode, cascadeIdle, waitForCascade } from "../api-runner.js";
4
+ import { extractAndCompileQueries } from "../query/compile.js";
5
+ import { graphqlEnvFile } from "../query/graphql-env.js";
6
+ import { clearDocumentCache, graphqlForApis, runGraphQL } from "../query/graphql-runner.js";
7
+ import { emitter, store } from "../redux/index.js";
8
+ import reporter from "../reporter.js";
9
+ import { buildSchema } from "../schema/index.js";
10
+ import { createViteConfig } from "../vite/config.js";
11
+ import { getRenderer } from "../renderer.js";
12
+ import { VIRTUAL, getPageComponents, invalidateVirtualModule, scanJsxInJsPlugin } from "../vite/plugin.js";
13
+ import { clientEntry, ssrEntry } from "../vite/paths.js";
14
+ import { pick } from "../../runtime/router/utils.js";
15
+ import { pageFileExtensions } from "../internal-plugins/page-creator.js";
16
+ import { slash, trailingSlashRedirect } from "../utils/paths.js";
17
+ import { DEV_STATEFUL_TRACE_ID, deletePage } from "../actions/index.js";
18
+ import { createApp } from "./express-compat.js";
19
+ import { createDevSsrRunner } from "./ssr-runner.js";
20
+ import { createHydrationReportListener } from "./hydration-report.js";
21
+ import { graphiqlHtml } from "./graphiql.js";
22
+ import { localUrl } from "./local-url.js";
23
+ import { runtimeName } from "../utils/runtime.js";
24
+ import { HYDRATION_EVENT } from "../../runtime/hydration-report.js";
25
+ import { compatEnv } from "../utils/env.js";
26
+ import { isKeptNotFoundMirror, isNotFoundPage, notFoundPagePaths, resolveNotFoundEntries, resolveNotFoundPages, runtimeNotFoundPages } from "../not-found-pages.js";
27
+ import { notFoundCandidates, notFoundLookupPath } from "../../runtime/not-found.js";
28
+ import path from "node:path";
29
+ import fs from "node:fs";
30
+ import { createServer, isCSSRequest } from "vite";
31
+ import http from "node:http";
32
+ import sirv from "sirv";
33
+ // src/node/develop/index.ts
34
+ /**
35
+ * Vite's dev-server URL of an absolute file outside the root: `/@fs/` + the path with forward
36
+ * slashes (`/@fs/home/x/a.js`; on Windows `/@fs/D:/x/a.js`, where `/@fs${path}` would give
37
+ * `/@fsD:/x/a.js`, which Vite can't load).
38
+ */
39
+ function fsUrl(file) {
40
+ return `/@fs/${slash(file).replace(/^\//, "")}`;
41
+ }
42
+ const isWindows = process.platform === "win32";
43
+ /** Windows paths are case-insensitive (NTFS), and their spelling can differ between sources */
44
+ const comparablePath = (p) => isWindows ? p.toLowerCase() : p;
45
+ /**
46
+ * The slashed spellings of a directory that paths of Vite's watcher can start with, comparable
47
+ * with {@link comparablePath}: as given, and its real paths – Vite watches its root realpath'd,
48
+ * which on Windows is fs.realpathSync.native, expanding 8.3 short names (C:/Users/RUNNER~1, e.g. in
49
+ * %TEMP%, becomes C:/Users/runneradmin), or fs.realpathSync, keeping them.
50
+ */
51
+ function watchedDirForms(dir) {
52
+ const forms = /* @__PURE__ */ new Set([slash(dir)]);
53
+ for (const real of [fs.realpathSync, fs.realpathSync.native]) try {
54
+ forms.add(slash(real(dir)));
55
+ } catch {}
56
+ return [...forms].map(comparablePath);
57
+ }
58
+ function findPageForPath(rawPath) {
59
+ const { pages } = store.getState();
60
+ let pathname = rawPath;
61
+ try {
62
+ pathname = decodeURIComponent(rawPath);
63
+ } catch {}
64
+ const candidates = [pathname, pathname.endsWith("/") ? pathname.slice(0, -1) : `${pathname}/`];
65
+ for (const c of candidates) {
66
+ const page = pages.get(c);
67
+ if (page) return page;
68
+ }
69
+ const notFound = notFoundPagePaths();
70
+ const routes = [...pages.values()].filter((p) => p.matchPath && !notFound.has(p.path)).map((p) => ({
71
+ path: p.matchPath,
72
+ page: p
73
+ }));
74
+ try {
75
+ return pick(routes, pathname)?.route.page;
76
+ } catch {
77
+ return;
78
+ }
79
+ }
80
+ /** the page an unknown URL gets: the 404 page of its section (`notFoundPages`) or of the site */
81
+ function notFoundPage(rawPath) {
82
+ const { pages } = store.getState();
83
+ const pathname = notFoundLookupPath(rawPath);
84
+ for (const p of notFoundCandidates(resolveNotFoundEntries(), pathname)) {
85
+ const page = pages.get(p);
86
+ if (page) return page;
87
+ }
88
+ return pages.get("/404/");
89
+ }
90
+ function dev404Html(pathname) {
91
+ const pages = [...store.getState().pages.keys()].sort();
92
+ const list = pages.slice(0, 300).map((p) => `<li><a href="${p}">${p}</a></li>`).join("");
93
+ return `<!doctype html><html><head><meta charset="utf-8"><title>404 – page not found</title><style>body{font-family:system-ui,sans-serif;max-width:48rem;margin:3rem auto;padding:0 1rem;line-height:1.5}code{background:#f2f2f2;padding:.1em .3em;border-radius:3px}</style></head><body><h1>404: page not found</h1><p>There's no page at <code>${pathname.replace(/</g, "&lt;")}</code> (development 404 page). Create a React component in <code>src/pages/404</code> to customize it.</p><p>${pages.length} pages exist:</p><ul>${list}</ul></body></html>`;
94
+ }
95
+ /**
96
+ * Like Gatsby's dev server: the files in public/ – e.g. images and linked files that plugins write
97
+ * to public/static (gatsby-remark-images, gatsby-remark-copy-linked-files, gatsby-plugin-sharp) or
98
+ * files written in onPostBootstrap. Looked up on each request (files appear while the server runs).
99
+ * Not HTML, directories or page-data: those may be left over from an earlier build, and develop
100
+ * renders pages and page-data itself. (static/ is served by Vite, as its publicDir.)
101
+ */
102
+ function publicFiles(publicDir) {
103
+ const files = sirv(publicDir, {
104
+ dev: true,
105
+ dotfiles: true,
106
+ etag: true,
107
+ extensions: []
108
+ });
109
+ return (req, res, next) => {
110
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
111
+ const pathname = (req.url ?? "/").split("?")[0];
112
+ if (pathname.endsWith("/") || !path.extname(pathname) || /\.html?$/i.test(pathname) || pathname.startsWith("/page-data/")) return next();
113
+ files(req, res, next);
114
+ };
115
+ }
116
+ /**
117
+ * `gatsby develop`: bootstrap, then serve pages through Vite with server-side rendering
118
+ * of the requested page (same React tree as the client → correct hydration & useId).
119
+ */
120
+ async function develop(options) {
121
+ process.env.NODE_ENV = "development";
122
+ if (options.reporter) reporter.setTransports(options.reporter);
123
+ const directory = path.resolve(options.directory);
124
+ const host = options.host ?? "localhost";
125
+ let port = options.port ?? 8e3;
126
+ await bootstrap({
127
+ directory,
128
+ command: "develop",
129
+ host,
130
+ port,
131
+ verbose: options.verbose,
132
+ prefixPaths: options.prefixPaths
133
+ });
134
+ const { config } = store.getState();
135
+ const devSSR = config.devSSR !== false;
136
+ const staticResults = /* @__PURE__ */ new Map();
137
+ let extraction = Promise.resolve();
138
+ async function runStaticQueries() {
139
+ const changed = [];
140
+ await Promise.all([...store.getState().staticQueryComponents.values()].map(async (sq) => {
141
+ const res = await runGraphQL(sq.query, {}, `sq--${sq.hash}`);
142
+ if (res.errors?.length) reporter.error(`Error in static query (${sq.componentPath}):\n${res.errors.map((e) => e.message).join("\n")}`);
143
+ const prev = staticResults.get(sq.hash);
144
+ if (JSON.stringify(prev) !== JSON.stringify(res.data)) changed.push(sq.hash);
145
+ staticResults.set(sq.hash, res.data);
146
+ }));
147
+ return changed;
148
+ }
149
+ await runStaticQueries();
150
+ const pageDataCache = /* @__PURE__ */ new Map();
151
+ async function getPageData(page) {
152
+ let cached = pageDataCache.get(page.path);
153
+ if (!cached) {
154
+ cached = (async () => {
155
+ await extraction;
156
+ const component = store.getState().components.get(page.componentPath);
157
+ let data;
158
+ if (component?.query) {
159
+ const res = await runGraphQL(component.query, {
160
+ ...page,
161
+ ...page.context
162
+ }, page.path);
163
+ if (res.errors?.length) reporter.error(`Error running page query for "${page.path}":\n${res.errors.map((e) => e.message).join("\n")}`);
164
+ data = res.data;
165
+ }
166
+ return {
167
+ componentChunkName: page.componentChunkName,
168
+ path: page.path,
169
+ ...page.matchPath ? { matchPath: page.matchPath } : {},
170
+ result: {
171
+ data,
172
+ pageContext: page.context
173
+ },
174
+ staticQueryHashes: [],
175
+ slicesMap: {}
176
+ };
177
+ })();
178
+ pageDataCache.set(page.path, cached);
179
+ cached.catch(() => pageDataCache.delete(page.path));
180
+ }
181
+ return cached;
182
+ }
183
+ const app = createApp();
184
+ const httpServer = http.createServer(app);
185
+ const viteConfig = await createViteConfig({
186
+ stage: "develop",
187
+ ctx: {
188
+ command: "develop",
189
+ buildHash: "develop",
190
+ devSSR,
191
+ getStaticQueryResult: (hash) => staticResults.get(hash)
192
+ }
193
+ });
194
+ const browserFiles = store.getState().flattenedPlugins.map((p) => p.gatsbyBrowserPath).filter(Boolean);
195
+ const { config: siteConfig } = store.getState();
196
+ const scanOptions = viteConfig.optimizeDeps?.rolldownOptions;
197
+ viteConfig.optimizeDeps = {
198
+ ...viteConfig.optimizeDeps,
199
+ rolldownOptions: {
200
+ ...scanOptions,
201
+ plugins: [...[scanOptions?.plugins ?? []].flat(), scanJsxInJsPlugin({
202
+ jsxRuntime: siteConfig.jsxRuntime,
203
+ jsxImportSource: siteConfig.jsxImportSource
204
+ })]
205
+ },
206
+ entries: [.../* @__PURE__ */ new Set([
207
+ ...[...getPageComponents().values()].map((c) => c.split("?")[0]),
208
+ ...browserFiles,
209
+ clientEntry,
210
+ getRenderer().runtime.shared,
211
+ getRenderer().runtime.client
212
+ ])].map(slash)
213
+ };
214
+ viteConfig.server = {
215
+ ...viteConfig.server,
216
+ hmr: { server: httpServer }
217
+ };
218
+ const vite = await createServer(viteConfig);
219
+ const ssrRunner = createDevSsrRunner(vite.environments.ssr);
220
+ vite.environments.client.hot.on(HYDRATION_EVENT, createHydrationReportListener((text) => reporter.warn(text)));
221
+ const clientWarmed = /* @__PURE__ */ new Set();
222
+ async function collectCss(componentPath) {
223
+ const seen = /* @__PURE__ */ new Set();
224
+ const cssIds = [];
225
+ const visit = (mod) => {
226
+ if (!mod || seen.has(mod.id ?? mod.url)) return;
227
+ seen.add(mod.id ?? mod.url);
228
+ if (mod.id && isCSSRequest(mod.id) && !/[?&](inline|raw|url)\b/.test(mod.id)) cssIds.push(mod.id);
229
+ for (const dep of mod.importedModules ?? []) visit(dep);
230
+ };
231
+ const toUrl = (file) => slash(file).startsWith(`${slash(directory)}/`) ? `/${slash(path.relative(directory, file))}` : fsUrl(file);
232
+ for (const file of [componentPath.split("?")[0], ssrEntry]) for (const mod of vite.environments.ssr.moduleGraph.getModulesByFile(slash(file)) ?? []) visit(mod);
233
+ for (const file of browserFiles) {
234
+ if (!clientWarmed.has(file)) {
235
+ clientWarmed.add(file);
236
+ try {
237
+ await vite.environments.client.transformRequest(toUrl(file));
238
+ } catch {}
239
+ }
240
+ for (const mod of vite.environments.client.moduleGraph.getModulesByFile(slash(file)) ?? []) visit(mod);
241
+ }
242
+ return (await Promise.all([...new Set(cssIds)].map(async (id) => {
243
+ try {
244
+ const url = toUrl(id.split("?")[0]);
245
+ return `<style type="text/css" data-vite-dev-id="${id}">${(await vite.transformRequest(`${url}${url.includes("?") ? "&" : "?"}direct`))?.code ?? ""}</style>`;
246
+ } catch {
247
+ return "";
248
+ }
249
+ }))).join("");
250
+ }
251
+ async function renderHtml(url, page, status = 200) {
252
+ const pageData = await getPageData(page);
253
+ const clientScript = fsUrl(clientEntry);
254
+ let html;
255
+ if (devSSR) try {
256
+ html = (await (await ssrRunner.import(ssrEntry)).renderPage({
257
+ pagePath: page.path,
258
+ url: url.split("?")[0],
259
+ notFound: status === 404 && isNotFoundPage(page.path),
260
+ pageData,
261
+ scripts: [clientScript],
262
+ headHtml: await collectCss(page.componentPath),
263
+ inlinePageData: true,
264
+ buildHash: "develop",
265
+ generator: "goatly (develop)"
266
+ })).html;
267
+ } catch (e) {
268
+ if (e instanceof Error) try {
269
+ vite.ssrFixStacktrace(e);
270
+ } catch {}
271
+ reporter.error({
272
+ context: { sourceMessage: `There was an error server-rendering "${page.path}" – falling back to client-side rendering` },
273
+ error: e
274
+ });
275
+ html = shellHtml(page.path, pageData, clientScript);
276
+ }
277
+ else html = shellHtml(page.path, pageData, clientScript);
278
+ return {
279
+ status,
280
+ html: await vite.transformIndexHtml(url, html)
281
+ };
282
+ }
283
+ function shellHtml(pagePath, pageData, clientScript) {
284
+ return `<!DOCTYPE html><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/></head><body><div id="___gatsby"></div><script>window.pagePath=${JSON.stringify(pagePath)};window.___pageData=${JSON.stringify(pageData).replace(/</g, "\\u003c")};<\/script><script type="module" src="${clientScript}"><\/script></body></html>`;
285
+ }
286
+ app.use(async (req, res, next) => {
287
+ const pathname = (req.url ?? "/").split("?")[0];
288
+ try {
289
+ if (pathname === "/___graphql" || pathname === "/__graphql") {
290
+ if (req.method === "GET" && !req.query.query) return res.type("html").send(graphiqlHtml(pathname));
291
+ let body = {};
292
+ if (req.method === "POST") {
293
+ const chunks = [];
294
+ for await (const chunk of req) chunks.push(chunk);
295
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
296
+ } else body = {
297
+ query: req.query.query,
298
+ variables: req.query.variables ? JSON.parse(req.query.variables) : {}
299
+ };
300
+ const result = await runGraphQL(body.query, body.variables ?? {}, "/___graphql");
301
+ return res.json({
302
+ ...result,
303
+ errors: result.errors?.map((e) => ({
304
+ message: e.message,
305
+ locations: e.locations,
306
+ path: e.path
307
+ }))
308
+ });
309
+ }
310
+ if (pathname === "/__refresh" && req.method === "POST") {
311
+ if (compatEnv("ENABLE_GOATLY_REFRESH_ENDPOINT") || compatEnv("GOATLY_EXPERIMENTAL_ENABLE_REFRESH")) {
312
+ const chunks = [];
313
+ for await (const chunk of req) chunks.push(chunk);
314
+ let webhookBody = {};
315
+ try {
316
+ webhookBody = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
317
+ } catch {}
318
+ activeSourcing++;
319
+ try {
320
+ await reloadData(webhookBody);
321
+ } finally {
322
+ activeSourcing--;
323
+ }
324
+ scheduleRefresh();
325
+ return res.status(200).send("ok");
326
+ }
327
+ return res.status(404).send("Refresh endpoint disabled. Set ENABLE_GOATLY_REFRESH_ENDPOINT=true (or ENABLE_GATSBY_REFRESH_ENDPOINT=true)");
328
+ }
329
+ if (pathname.startsWith("/page-data/")) {
330
+ if (pathname === "/page-data/app-data.json") return res.json({ webpackCompilationHash: "develop" });
331
+ const sq = /^\/page-data\/sq\/d\/(.+)\.json$/.exec(pathname);
332
+ if (sq) return res.json({ data: staticResults.get(sq[1]) });
333
+ const m = /^\/page-data\/(.*)\/page-data\.json$/.exec(pathname);
334
+ if (m) {
335
+ const page = findPageForPath(m[1] === "index" ? "/" : `/${m[1]}`);
336
+ if (!page) return res.status(404).json({});
337
+ res.setHeader("Cache-Control", "no-store");
338
+ return res.json(await getPageData(page));
339
+ }
340
+ }
341
+ } catch (e) {
342
+ return next(e);
343
+ }
344
+ next();
345
+ });
346
+ await apiRunnerNode("onCreateDevServer", {
347
+ app,
348
+ store,
349
+ graphql: graphqlForApis
350
+ });
351
+ if (typeof config.developMiddleware === "function") config.developMiddleware(app);
352
+ const servePublicFiles = publicFiles(store.getState().program.publicDir);
353
+ const siteStatic = path.join(directory, "static");
354
+ app.use((req, res, next) => {
355
+ const url = req.url ?? "";
356
+ if (!url.startsWith("/static/")) return next();
357
+ let pathname = url.split("?")[0];
358
+ try {
359
+ pathname = decodeURIComponent(pathname);
360
+ } catch {}
361
+ const own = path.join(siteStatic, pathname);
362
+ if (own.startsWith(`${siteStatic}${path.sep}`) && fs.existsSync(own)) return next();
363
+ servePublicFiles(req, res, next);
364
+ });
365
+ app.use(vite.middlewares);
366
+ app.use(servePublicFiles);
367
+ app.use(async (req, res, next) => {
368
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
369
+ const accept = String(req.headers.accept ?? "");
370
+ const pathname = (req.url ?? "/").split("?")[0];
371
+ if (!accept.includes("text/html") && !pathname.endsWith("/") && path.extname(pathname)) return next();
372
+ try {
373
+ const canonical = trailingSlashRedirect(pathname, store.getState().config.trailingSlash);
374
+ if (canonical && findPageForPath(canonical)) {
375
+ const search = (req.url ?? "").slice(pathname.length);
376
+ return res.redirect(301, `${canonical}${search}`);
377
+ }
378
+ let page = findPageForPath(pathname);
379
+ let status = 200;
380
+ if (!page) {
381
+ status = 404;
382
+ page = notFoundPage(pathname);
383
+ if (!page) return res.status(404).type("html").send(dev404Html(pathname));
384
+ }
385
+ const { html } = await renderHtml(req.url ?? pathname, page, status);
386
+ res.status(status).type("html").send(html);
387
+ } catch (e) {
388
+ next(e);
389
+ }
390
+ });
391
+ let refreshing = false;
392
+ /** /__refresh requests running sourceNodes */
393
+ let activeSourcing = 0;
394
+ let refreshTimer;
395
+ let queued = false;
396
+ const notifyClients = () => vite.environments.client.hot.send({
397
+ type: "custom",
398
+ event: "goatly:data-update",
399
+ data: {}
400
+ });
401
+ async function refreshQueries() {
402
+ extraction = (async () => {
403
+ clearDocumentCache();
404
+ await extractAndCompileQueries();
405
+ })();
406
+ await extraction;
407
+ const changed = await runStaticQueries();
408
+ for (const hash of changed) await invalidateVirtualModule(vite, `${VIRTUAL.staticQueryPrefix}${hash}`);
409
+ pageDataCache.clear();
410
+ }
411
+ async function refreshPages() {
412
+ const before = new Map(store.getState().pages);
413
+ const createdBefore = [...before.values()].filter((p) => !p.isCreatedByStatefulCreatePages).map((p) => p.path);
414
+ const touched = /* @__PURE__ */ new Set();
415
+ const onCreate = (action) => touched.add(action.payload.path);
416
+ emitter.on("CREATE_PAGE", onCreate);
417
+ try {
418
+ await apiRunnerNode("createPages", {
419
+ graphql: graphqlForApis,
420
+ traceId: "dev-createPages",
421
+ waitForCascadingActions: true
422
+ });
423
+ await waitForCascade("dev-createPages");
424
+ } finally {
425
+ emitter.off("CREATE_PAGE", onCreate);
426
+ }
427
+ const unflagged = new Set(createdBefore);
428
+ const kept = (p) => touched.has(p) || !unflagged.has(p) && store.getState().pages.has(p);
429
+ for (const p of createdBefore) {
430
+ if (touched.has(p)) continue;
431
+ const page = store.getState().pages.get(p);
432
+ if (page && isKeptNotFoundMirror(page, kept)) continue;
433
+ deletePage({ path: p });
434
+ }
435
+ if ([...getPageComponents().keys()].sort().join() !== [...new Set([...before.values()].map((p) => p.componentChunkName))].sort().join()) await invalidateVirtualModule(vite, VIRTUAL.asyncRequires);
436
+ await syncNotFoundPages();
437
+ }
438
+ let notFoundJson = JSON.stringify(runtimeNotFoundPages());
439
+ let notFoundReport = resolveNotFoundPages().problems.join("\n");
440
+ async function syncNotFoundPages() {
441
+ const json = JSON.stringify(runtimeNotFoundPages());
442
+ if (json !== notFoundJson) {
443
+ notFoundJson = json;
444
+ await invalidateVirtualModule(vite, VIRTUAL.notFoundPages);
445
+ }
446
+ const report = resolveNotFoundPages().problems.join("\n");
447
+ if (report && report !== notFoundReport) reporter.warn(report);
448
+ notFoundReport = report;
449
+ }
450
+ /** the running refresh (onDataChange), resolved when it ends */
451
+ let runningRefresh;
452
+ /** a running data reload (/__refresh): no schema is built meanwhile */
453
+ let reloading;
454
+ /**
455
+ * Gatsby's data reload: createSchemaCustomization again on a cleared customization (e.g. types a
456
+ * source plugin declares from a remote content model), then sourcing. The schema is built after
457
+ * it (types a plugin still declares in sourceNodes are back by then). One reload at a time, and
458
+ * not while a refresh builds the schema with the current customization.
459
+ */
460
+ async function reloadData(webhookBody) {
461
+ while (runningRefresh || reloading) await Promise.all([runningRefresh, reloading?.catch(() => {})]);
462
+ const run = (async () => {
463
+ store.dispatch({ type: "CLEAR_SCHEMA_CUSTOMIZATION" });
464
+ await apiRunnerNode("createSchemaCustomization", { traceId: "refresh-createSchemaCustomization" });
465
+ await apiRunnerNode("sourceNodes", {
466
+ traceId: "refresh-sourceNodes",
467
+ waitForCascadingActions: true,
468
+ webhookBody
469
+ });
470
+ })();
471
+ reloading = run;
472
+ try {
473
+ await run;
474
+ } finally {
475
+ if (reloading === run) reloading = void 0;
476
+ }
477
+ }
478
+ async function onDataChange() {
479
+ if (refreshing) {
480
+ queued = true;
481
+ return;
482
+ }
483
+ refreshing = true;
484
+ let refreshEnded;
485
+ runningRefresh = new Promise((resolve) => refreshEnded = resolve);
486
+ let activity;
487
+ try {
488
+ await waitForCascade();
489
+ while (reloading) await reloading.catch(() => {});
490
+ activity = reporter.activityTimer("refreshing data");
491
+ activity.start();
492
+ await buildSchema();
493
+ await refreshPages();
494
+ await refreshQueries();
495
+ notifyClients();
496
+ activity.end();
497
+ } catch (e) {
498
+ if (activity) reporter.endActivity(activity, "failed");
499
+ reporter.error(e);
500
+ } finally {
501
+ refreshing = false;
502
+ runningRefresh = void 0;
503
+ refreshEnded();
504
+ if (queued) {
505
+ queued = false;
506
+ scheduleRefresh();
507
+ }
508
+ }
509
+ }
510
+ function scheduleRefresh() {
511
+ clearTimeout(refreshTimer);
512
+ refreshTimer = setTimeout(onDataChange, 50);
513
+ }
514
+ const isInternal = (action) => refreshing || action.plugin?.name === "internal-data-bridge" || action.payload?.internal?.type === "SitePage";
515
+ for (const type of [
516
+ "CREATE_NODE",
517
+ "DELETE_NODE",
518
+ "ADD_FIELD_TO_NODE",
519
+ "ADD_CHILD_NODE_TO_PARENT_NODE"
520
+ ]) emitter.on(type, (action) => {
521
+ if (!isInternal(action)) scheduleRefresh();
522
+ });
523
+ const pageDirs = store.getState().flattenedPlugins.filter((p) => p.name === "gatsby-plugin-page-creator").flatMap((p) => watchedDirForms(p.resolve));
524
+ const pageExtensions = new Set(pageFileExtensions());
525
+ let fileTimer;
526
+ const pendingFiles = /* @__PURE__ */ new Set();
527
+ let pageFilesChanged = false;
528
+ const restartFiles = watchedDirForms(directory).flatMap((d) => ["gatsby-config", "gatsby-node"].map((b) => `${d}/${comparablePath(b)}`));
529
+ const envFile = graphqlEnvFile(directory, store.getState().config.gqlTada);
530
+ const generatedFiles = envFile ? watchedDirForms(path.dirname(envFile)).map((d) => `${d}/${comparablePath(path.basename(envFile))}`) : [];
531
+ vite.watcher.on("all", (event, file) => {
532
+ const f = slash(file);
533
+ if (f.includes("/node_modules/") || f.includes("/.cache/") || f.includes("/public/")) return;
534
+ const key = comparablePath(f);
535
+ if (generatedFiles.includes(key)) return;
536
+ if (restartFiles.some((r) => key.startsWith(`${r}.`))) {
537
+ reporter.warn(`${path.basename(f)} changed – restart "goatly develop" to apply the change.`);
538
+ return;
539
+ }
540
+ const pageFile = (event === "add" || event === "unlink") && pageDirs.some((d) => key.startsWith(`${d}/`)) && pageExtensions.has(path.extname(f));
541
+ if (!pageFile && !/\.(m|c)?[jt]sx?$/.test(f)) return;
542
+ if (pageFile) pageFilesChanged = true;
543
+ pendingFiles.add(f);
544
+ clearTimeout(fileTimer);
545
+ fileTimer = setTimeout(async () => {
546
+ const files = [...pendingFiles];
547
+ pendingFiles.clear();
548
+ const pagesChanged = pageFilesChanged;
549
+ pageFilesChanged = false;
550
+ try {
551
+ if (pagesChanged) {
552
+ const state = store.getState();
553
+ for (const page of state.pages.values()) if (page.isCreatedByStatefulCreatePages && !fs.existsSync(page.componentPath.split("?")[0])) deletePage(page);
554
+ await apiRunnerNode("createPagesStatefully", {
555
+ graphql: graphqlForApis,
556
+ traceId: DEV_STATEFUL_TRACE_ID,
557
+ waitForCascadingActions: true
558
+ });
559
+ await refreshPages();
560
+ await invalidateVirtualModule(vite, VIRTUAL.asyncRequires);
561
+ notifyClients();
562
+ }
563
+ if (files.length) {
564
+ const before = JSON.stringify([...store.getState().components.values()].map((c) => c.query));
565
+ await refreshQueries();
566
+ if (before !== JSON.stringify([...store.getState().components.values()].map((c) => c.query))) notifyClients();
567
+ }
568
+ } catch (e) {
569
+ reporter.error(e);
570
+ }
571
+ }, 60);
572
+ });
573
+ for (let attempt = 0; attempt < 20; attempt++) try {
574
+ await new Promise((resolve, reject) => {
575
+ httpServer.once("error", reject);
576
+ httpServer.listen(port, host, () => {
577
+ httpServer.off("error", reject);
578
+ resolve();
579
+ });
580
+ });
581
+ break;
582
+ } catch (e) {
583
+ if (e?.code !== "EADDRINUSE") throw e;
584
+ reporter.warn(`Port ${port} is in use, trying ${port + 1}`);
585
+ port++;
586
+ }
587
+ store.dispatch({
588
+ type: "SET_PROGRAM",
589
+ payload: { port }
590
+ });
591
+ const url = localUrl(host, port);
592
+ vite.resolvedUrls = {
593
+ local: [url],
594
+ network: []
595
+ };
596
+ const devServer = {
597
+ server: httpServer,
598
+ vite,
599
+ port,
600
+ async close() {
601
+ await ssrRunner.close();
602
+ await vite.close();
603
+ const closed = new Promise((r) => httpServer.close(r));
604
+ httpServer.closeAllConnections?.();
605
+ await closed;
606
+ if (!refreshing && activeSourcing === 0 && cascadeIdle()) await persistState();
607
+ else reporter.warn("Data was still being refreshed: this session's nodes and caches are not kept");
608
+ finishCaches();
609
+ }
610
+ };
611
+ options.onReady?.(devServer);
612
+ const viteVersion = (await import("vite")).version;
613
+ reporter.log("");
614
+ reporter.success(`You can now view your site in the browser:\n\n ${url}\n\n View GraphiQL, an in-browser IDE, to explore your site's data and schema\n\n ${url}___graphql\n`);
615
+ reporter.info(`development server running on ${runtimeName} (Vite ${viteVersion})`);
616
+ return devServer;
617
+ }
618
+ export { develop };
@@ -0,0 +1,10 @@
1
+ // src/node/develop/local-url.ts
2
+ /**
3
+ * The site's URL as develop prints it: a wildcard host (all interfaces) as localhost, an IPv6
4
+ * address in brackets.
5
+ */
6
+ function localUrl(host, port) {
7
+ const name = host === "" || host === "0.0.0.0" || host === "::" || host === "[::]" ? "localhost" : host;
8
+ return `http://${name.includes(":") && !name.startsWith("[") ? `[${name}]` : name}:${port}/`;
9
+ }
10
+ export { localUrl };
@@ -0,0 +1,66 @@
1
+ import { createRequire } from "node:module";
2
+ import { fileURLToPath } from "node:url";
3
+ import { createServerModuleRunner } from "vite";
4
+ import { ESModulesEvaluator } from "vite/module-runner";
5
+ // src/node/develop/ssr-runner.ts
6
+ const nodeRequire = createRequire(import.meta.url);
7
+ /**
8
+ * Is `ns` what Node's `import()` returned for a CommonJS file? Vite externalizes dependencies as
9
+ * `file://` URLs, and Node loads CommonJS through its CommonJS loader, whose cache then holds the
10
+ * module – with `module.exports` as the namespace's default. Native ES modules aren't there (and
11
+ * Bun, which applies this interop itself, gives another default).
12
+ */
13
+ function isCommonJsNamespace(url, ns) {
14
+ if (!url.startsWith("file:")) return false;
15
+ let file;
16
+ try {
17
+ file = fileURLToPath(url);
18
+ } catch {
19
+ return false;
20
+ }
21
+ const cached = nodeRequire.cache[file];
22
+ return cached !== void 0 && cached.exports === ns?.default;
23
+ }
24
+ /**
25
+ * Applies webpack-style CommonJS interop to the namespace Node returns for a CommonJS external
26
+ * (see isCommonJsNamespace – ES modules are left as they are), so dev SSR
27
+ * accepts the same imports as Gatsby's webpack and the production build (bundled, `ssr.noExternal: true`):
28
+ *
29
+ * - default import: Node yields `module.exports`. For CommonJS compiled from ESM
30
+ * (`exports.__esModule = true; exports.default = ...`, e.g. styled-components 5) webpack resolved
31
+ * it to `exports.default` (otherwise `styled.div is not a function`).
32
+ * - named imports: Node only exposes the names its static lexer detects, so re-exports via
33
+ * `require()` (e.g. `@apollo/client/main.cjs`) are missing ("Named export 'ApolloProvider' not
34
+ * found"). webpack allowed any property of `module.exports`.
35
+ */
36
+ function interopExternalNamespace(ns) {
37
+ const cjs = ns?.default;
38
+ if (cjs == null || typeof cjs !== "object" && typeof cjs !== "function") return ns;
39
+ const unwrapDefault = !!cjs.__esModule && "default" in cjs;
40
+ const missing = Object.keys(cjs).filter((k) => k !== "default" && k !== "__esModule" && !(k in ns));
41
+ if (!unwrapDefault && missing.length === 0) return ns;
42
+ const out = Object.create(null);
43
+ const define = (key, get) => Object.defineProperty(out, key, {
44
+ enumerable: true,
45
+ get
46
+ });
47
+ for (const key of missing) define(key, () => cjs[key]);
48
+ for (const key of Object.keys(ns)) if (!(unwrapDefault && key === "default")) define(key, () => ns[key]);
49
+ if (unwrapDefault) define("default", () => cjs.default);
50
+ Object.defineProperty(out, Symbol.toStringTag, { value: "Module" });
51
+ return Object.freeze(out);
52
+ }
53
+ /** The namespace dev SSR gets for an external: interop for CommonJS, ES modules unchanged. */
54
+ function externalNamespace(url, ns) {
55
+ return isCommonJsNamespace(url, ns) ? interopExternalNamespace(ns) : ns;
56
+ }
57
+ var InteropEvaluator = class extends ESModulesEvaluator {
58
+ async runExternalModule(filepath) {
59
+ return externalNamespace(filepath, await super.runExternalModule(filepath));
60
+ }
61
+ };
62
+ /** Module runner for dev SSR: Vite's default runner, plus CommonJS default-import interop for externals. */
63
+ function createDevSsrRunner(environment) {
64
+ return createServerModuleRunner(environment, { evaluator: new InteropEvaluator() });
65
+ }
66
+ export { createDevSsrRunner, externalNamespace, interopExternalNamespace, isCommonJsNamespace };