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,79 @@
1
+ import { createNodeId } from "../utils/create-node-id.js";
2
+ import { slash } from "../utils/paths.js";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
5
+ import fs from "node:fs";
6
+ // src/node/plugins/resolve-plugin.ts
7
+ function readJson(file) {
8
+ return JSON.parse(fs.readFileSync(file, "utf8"));
9
+ }
10
+ /** Looks a package up in node_modules folders walking up from `fromDir` (ignores `exports` restrictions). */
11
+ function findPackageDir(name, fromDir) {
12
+ let dir = path.resolve(fromDir);
13
+ while (true) {
14
+ const candidate = path.join(dir, "node_modules", name);
15
+ if (fs.existsSync(path.join(candidate, "package.json"))) return fs.realpathSync(candidate);
16
+ const parent = path.dirname(dir);
17
+ if (parent === dir) break;
18
+ dir = parent;
19
+ }
20
+ try {
21
+ const req = createRequire(path.join(fromDir, "noop.js"));
22
+ let p = path.dirname(req.resolve(name));
23
+ while (p !== path.dirname(p)) {
24
+ if (fs.existsSync(path.join(p, "package.json"))) {
25
+ if (readJson(path.join(p, "package.json")).name === name) return p;
26
+ }
27
+ p = path.dirname(p);
28
+ }
29
+ } catch {}
30
+ }
31
+ function createPluginId(name, plugin) {
32
+ return createNodeId(name + (plugin && typeof plugin === "object" ? JSON.stringify(plugin.options ?? {}) : ""), "Plugin");
33
+ }
34
+ /** Same resolution algorithm as Gatsby's `resolvePlugin` (local `plugins/` dir first, then node_modules). */
35
+ function resolvePlugin(pluginName, rootDir) {
36
+ if (path.isAbsolute(pluginName) || pluginName.startsWith(".")) {
37
+ let dir = path.resolve(rootDir, pluginName);
38
+ if (fs.existsSync(dir) && fs.statSync(dir).isFile()) dir = path.dirname(dir);
39
+ if (!fs.existsSync(dir)) throw new Error(`Unable to find plugin at "${pluginName}"`);
40
+ return fromDir(dir, path.basename(dir));
41
+ }
42
+ const local = path.join(rootDir, "plugins", pluginName);
43
+ if (fs.existsSync(local)) return fromDir(local, pluginName);
44
+ const dir = findPackageDir(pluginName, rootDir);
45
+ if (!dir) throw new Error(`Unable to find plugin "${pluginName}". Perhaps you need to install its package?`);
46
+ return fromDir(dir, pluginName);
47
+ }
48
+ function fromDir(dir, fallbackName) {
49
+ let packageJson = {};
50
+ const pkgFile = path.join(dir, "package.json");
51
+ if (fs.existsSync(pkgFile)) packageJson = readJson(pkgFile);
52
+ const name = packageJson.name ?? fallbackName;
53
+ return {
54
+ resolve: slash(dir),
55
+ name,
56
+ version: packageJson.version ?? "1.0.0",
57
+ id: createPluginId(name),
58
+ packageJson
59
+ };
60
+ }
61
+ /** Resolves a sub-plugin module entry (e.g. gatsby-remark-* main file). */
62
+ function resolvePluginModulePath(info, entry) {
63
+ const req = createRequire(path.join(info.resolve, "package.json"));
64
+ try {
65
+ return req.resolve(entry ? path.join(info.resolve, entry) : info.resolve);
66
+ } catch {
67
+ for (const ext of [
68
+ ".ts",
69
+ ".mts",
70
+ ".js",
71
+ ".mjs",
72
+ ".cjs"
73
+ ]) {
74
+ const f = path.join(info.resolve, (entry ?? "index") + ext);
75
+ if (fs.existsSync(f)) return f;
76
+ }
77
+ }
78
+ }
79
+ export { createPluginId, findPackageDir, resolvePlugin, resolvePluginModulePath };
@@ -0,0 +1,64 @@
1
+ import { parseSync } from "../utils/parser.js";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ // src/node/plugins/static-exports.ts
5
+ /**
6
+ * oxc language of a source file. JavaScript files may contain JSX (as in Gatsby), which oxc only
7
+ * parses when asked to: with the language taken from a .js extension a file with JSX parses to nothing.
8
+ */
9
+ function sourceLang(file) {
10
+ const ext = path.extname(file);
11
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts") return "ts";
12
+ if (ext === ".tsx") return "tsx";
13
+ return "jsx";
14
+ }
15
+ /**
16
+ * Statically detects the exported names of an ESM or CommonJS module without running it.
17
+ * Used for gatsby-browser / gatsby-ssr files which import React, CSS etc., and for the
18
+ * exports of page components. `code` is the module's source when the caller already read it.
19
+ */
20
+ function getStaticExports(file, code) {
21
+ if (code === void 0) try {
22
+ code = fs.readFileSync(file, "utf8");
23
+ } catch {
24
+ return [];
25
+ }
26
+ const names = /* @__PURE__ */ new Set();
27
+ let result;
28
+ try {
29
+ result = parseSync(file, code, { lang: sourceLang(file) });
30
+ } catch {
31
+ return [];
32
+ }
33
+ const program = result.program;
34
+ for (const stmt of program.body) if (stmt.type === "ExportNamedDeclaration") {
35
+ const decl = stmt.declaration;
36
+ if (decl?.type === "FunctionDeclaration" || decl?.type === "ClassDeclaration") {
37
+ if (decl.id) names.add(decl.id.name);
38
+ } else if (decl?.type === "VariableDeclaration") {
39
+ for (const d of decl.declarations) if (d.id.type === "Identifier") names.add(d.id.name);
40
+ }
41
+ for (const spec of stmt.specifiers ?? []) names.add(spec.exported.name ?? spec.exported.value);
42
+ } else if (stmt.type === "ExpressionStatement") collectCjs(stmt.expression, names);
43
+ return [...names];
44
+ }
45
+ function collectCjs(expr, names) {
46
+ if (expr?.type !== "AssignmentExpression") return;
47
+ const left = expr.left;
48
+ if (left.type === "MemberExpression" || left.type === "StaticMemberExpression") {
49
+ const obj = left.object;
50
+ const prop = left.property;
51
+ if ((obj.type === "Identifier" && obj.name === "exports" || (obj.type === "MemberExpression" || obj.type === "StaticMemberExpression") && obj.object?.name === "module" && obj.property?.name === "exports") && prop?.name) names.add(prop.name);
52
+ if (obj.type === "Identifier" && obj.name === "module" && prop?.name === "exports" && expr.right.type === "ObjectExpression") {
53
+ for (const p of expr.right.properties) if (p.key?.name) names.add(p.key.name);
54
+ else if (p.key?.value) names.add(p.key.value);
55
+ }
56
+ }
57
+ if (expr.right?.type === "AssignmentExpression") collectCjs(expr.right, names);
58
+ }
59
+ /** True when a file uses CommonJS exports and no ESM syntax. */
60
+ function isCommonJsSource(code) {
61
+ if (/^\s*(import\s|export\s)/m.test(code)) return false;
62
+ return /\b(module\.exports|exports\.[\w$]+\s*=|require\s*\()/.test(code);
63
+ }
64
+ export { getStaticExports, isCommonJsSource, sourceLang };
@@ -0,0 +1,326 @@
1
+ import { Kind, NoUnusedFragmentsRule, getNamedType, isAbstractType, isObjectType, parse, print, specifiedRules, validate } from "../gql.js";
2
+ import { store } from "../redux/index.js";
3
+ import reporter from "../reporter.js";
4
+ import { getSchema } from "../schema/index.js";
5
+ import { apiRunnerNode } from "../api-runner.js";
6
+ import { slash } from "../utils/paths.js";
7
+ import { getStaticExports } from "../plugins/static-exports.js";
8
+ import { extractFromSource, findQueryFiles } from "./extract.js";
9
+ import { readSitePageNodes } from "../site-page-nodes.js";
10
+ import { updateGraphQLEnv } from "./graphql-env.js";
11
+ import path from "node:path";
12
+ import fs from "node:fs";
13
+ // src/node/query/compile.ts
14
+ /** files with an exported query that no page uses as its component, noted once per process */
15
+ const notedNonPageQueries = /* @__PURE__ */ new Set();
16
+ /** files warned about: a module the bundles include, with an exported query that is ignored */
17
+ const warnedIgnoredPageQueries = /* @__PURE__ */ new Set();
18
+ /** real paths of component paths (createPage keeps the path it gets, e.g. through a symlink) */
19
+ const realPaths = /* @__PURE__ */ new Map();
20
+ function realPath(file) {
21
+ let real = realPaths.get(file);
22
+ if (real === void 0) {
23
+ try {
24
+ real = slash(fs.realpathSync(file));
25
+ } catch {
26
+ real = file;
27
+ }
28
+ realPaths.set(file, real);
29
+ }
30
+ return real;
31
+ }
32
+ /** whether `file` (a module id of Vite: a slashed real path) is the component of a page */
33
+ function isPageComponent(file) {
34
+ const components = [...store.getState().components.keys()].map((c) => c.split("?")[0]);
35
+ if (components.includes(file)) return true;
36
+ const real = realPath(file);
37
+ return components.some((c) => realPath(c) === real);
38
+ }
39
+ /**
40
+ * Warns (once per file) when a module the bundles include exports a page query but is not a page
41
+ * component: the query never runs, yet the site renders the module (a page, a layout or
42
+ * gatsby-browser imports it), e.g. a component that exports `query` instead of calling
43
+ * `useStaticQuery`. Called by the Vite plugin for the modules it compiles. A template that no page
44
+ * uses (e.g. for a content type the site's CMS has no entries of) is not bundled, so this is not
45
+ * called for it; the query extraction notes it in verbose output only.
46
+ */
47
+ function warnIfPageQueryIsIgnored(file) {
48
+ file = slash(file);
49
+ if (warnedIgnoredPageQueries.has(file) || isPageComponent(file)) return;
50
+ warnedIgnoredPageQueries.add(file);
51
+ reporter.warn(`Exported queries are only executed for page components – the query in "${file}" is ignored: the site imports this file, but no page uses it as its component. Use useStaticQuery (or a fragment in the page query) in other components.`);
52
+ }
53
+ const rules = specifiedRules.filter((r) => r !== NoUnusedFragmentsRule);
54
+ /**
55
+ * A validation rule that finds the selections of SitePage nodes: fields of type SitePage (e.g.
56
+ * `allSitePage { nodes }`, `sitePage`, a link to a page), fields of SitePage (e.g. in
57
+ * `parent { ... on SitePage { path } }`), and root fields over an interface or union that includes
58
+ * SitePage. (Other abstract fields, e.g. `parent`, read nodes by id: such reads are found when they
59
+ * happen.)
60
+ */
61
+ function sitePageSelections(schema, onFound) {
62
+ const sitePage = schema.getType("SitePage");
63
+ if (!sitePage || !isObjectType(sitePage)) return void 0;
64
+ const queryType = schema.getQueryType();
65
+ const includesSitePage = (type) => type === sitePage || isAbstractType(type) && schema.isSubType(type, sitePage);
66
+ return (context) => ({ Field() {
67
+ const type = context.getType();
68
+ if (!type) return;
69
+ const named = getNamedType(type);
70
+ const parent = context.getParentType();
71
+ if (named === sitePage || parent === sitePage) onFound();
72
+ else if (parent === queryType) {
73
+ const nodes = isObjectType(named) ? named.getFields().nodes : void 0;
74
+ if (includesSitePage(nodes ? getNamedType(nodes.type) : named)) onFound();
75
+ }
76
+ } });
77
+ }
78
+ function collectSpreads(node, out) {
79
+ if (!node || typeof node !== "object") return;
80
+ if (Array.isArray(node)) {
81
+ for (const n of node) collectSpreads(n, out);
82
+ return;
83
+ }
84
+ if (node.kind === Kind.FRAGMENT_SPREAD) out.add(node.name.value);
85
+ for (const key of [
86
+ "selectionSet",
87
+ "selections",
88
+ "definitions"
89
+ ]) if (node[key]) collectSpreads(node[key], out);
90
+ }
91
+ const preprocessed = /* @__PURE__ */ new Map();
92
+ /**
93
+ * Runs `preprocessSource` for a file, once per contents in this process (like Gatsby, which only
94
+ * parses changed files again): query extraction and the StaticImage transform both need it.
95
+ */
96
+ function runPreprocessSource(file, contents) {
97
+ const key = slash(file);
98
+ const last = preprocessed.get(key);
99
+ if (last?.contents === contents) return last.results;
100
+ const results = apiRunnerNode("preprocessSource", {
101
+ filename: file,
102
+ contents
103
+ });
104
+ preprocessed.set(key, {
105
+ contents,
106
+ results
107
+ });
108
+ return results;
109
+ }
110
+ async function readSource(file) {
111
+ try {
112
+ let code = await fs.promises.readFile(file, "utf8");
113
+ if (store.getState().flattenedPlugins.some((p) => p.nodeAPIs.includes("preprocessSource"))) {
114
+ const processed = (await runPreprocessSource(file, code)).find((r) => typeof r === "string");
115
+ if (processed) code = processed;
116
+ }
117
+ return code;
118
+ } catch {
119
+ return;
120
+ }
121
+ }
122
+ /**
123
+ * Extracts and compiles all queries of the site:
124
+ * page queries of page components, static queries and fragments.
125
+ */
126
+ async function extractAndCompileQueries() {
127
+ const state = store.getState();
128
+ const siteDir = state.program.directory;
129
+ const pluginDirs = state.flattenedPlugins.map((p) => p.resolve).filter((d) => path.isAbsolute(d) && d !== siteDir && fs.existsSync(d));
130
+ const componentPaths = [...state.components.keys()].map((c) => c.split("?")[0]);
131
+ await apiRunnerNode("onPreExtractQueries", {});
132
+ const result = await compileFiles(await findQueryFiles(siteDir, pluginDirs, componentPaths), componentPaths);
133
+ await updateGraphQLEnv(result);
134
+ return result;
135
+ }
136
+ async function compileFiles(files, componentPaths) {
137
+ const fragments = /* @__PURE__ */ new Map();
138
+ const result = {
139
+ pageQueries: /* @__PURE__ */ new Map(),
140
+ staticQueries: /* @__PURE__ */ new Map(),
141
+ staticQueriesByFile: /* @__PURE__ */ new Map(),
142
+ fragments,
143
+ queries: /* @__PURE__ */ new Map(),
144
+ usesGraphqlTypes: false,
145
+ errors: 0
146
+ };
147
+ const parsed = [];
148
+ const components = new Set(componentPaths.map(slash));
149
+ const sources = await Promise.all(files.map(async (file) => ({
150
+ file,
151
+ code: await readSource(file)
152
+ })));
153
+ for (const { file, code } of sources) {
154
+ if (code === void 0) continue;
155
+ if (components.has(slash(file)) && code.includes("getServerData") && getStaticExports(file, code).includes("getServerData")) {
156
+ reporter.panicOnBuild({ context: { sourceMessage: `"${file}" exports getServerData, but goatly only builds static pages: server-side rendering (SSR) is not supported, and the page would render without its serverData.\n\nTo migrate, remove the getServerData export and either:\n - source the data at build time (sourceNodes) and read it with the page query, or\n - fetch it in the browser, e.g. in a useEffect.` } });
157
+ result.errors++;
158
+ }
159
+ const extraction = extractFromSource(file, code);
160
+ if (extraction.error) {
161
+ if (components.has(slash(file))) {
162
+ reporter.panicOnBuild({
163
+ context: { sourceMessage: `Could not extract queries from "${file}"` },
164
+ error: extraction.error
165
+ });
166
+ result.errors++;
167
+ } else reporter.verbose(`Skipping query extraction for ${file}: ${extraction.error.message}`);
168
+ continue;
169
+ }
170
+ for (const message of extraction.callErrors ?? []) {
171
+ reporter.panicOnBuild({
172
+ id: "85911",
173
+ context: { sourceMessage: message }
174
+ });
175
+ result.errors++;
176
+ }
177
+ if (extraction.usesRegistry) result.usesGraphqlTypes = true;
178
+ for (const tag of extraction.tags) {
179
+ if (tag.call) result.usesGraphqlTypes = true;
180
+ const entry = {
181
+ ...tag,
182
+ file
183
+ };
184
+ try {
185
+ entry.document = parse(tag.text);
186
+ } catch (e) {
187
+ reporter.panicOnBuild({
188
+ id: "85911",
189
+ context: { sourceMessage: `GraphQL syntax error in "${file}": ${e.message}` }
190
+ });
191
+ result.errors++;
192
+ continue;
193
+ }
194
+ for (const def of entry.document.definitions) {
195
+ if (def.kind === Kind.OPERATION_DEFINITION && def.operation === "query" && def.name) {
196
+ const printed = print(def);
197
+ const existing = result.queries.get(def.name.value);
198
+ result.queries.set(def.name.value, existing === void 0 || existing === printed ? printed : null);
199
+ }
200
+ if (def.kind === Kind.FRAGMENT_DEFINITION) {
201
+ const existing = fragments.get(def.name.value);
202
+ if (existing && print(existing.def) !== print(def)) {
203
+ reporter.panicOnBuild({
204
+ id: "85908",
205
+ context: { sourceMessage: `There are multiple fragments with the name "${def.name.value}".\n - ${existing.file}\n - ${file}` }
206
+ });
207
+ result.errors++;
208
+ }
209
+ fragments.set(def.name.value, {
210
+ def,
211
+ file
212
+ });
213
+ }
214
+ }
215
+ parsed.push(entry);
216
+ }
217
+ }
218
+ const schema = getSchema();
219
+ const compile = (tag) => {
220
+ const doc = tag.document;
221
+ const ops = doc.definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION);
222
+ const needed = /* @__PURE__ */ new Set();
223
+ const ownFragments = new Set(doc.definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((d) => d.name.value));
224
+ collectSpreads(ops, needed);
225
+ for (const n of ownFragments) collectSpreads(doc.definitions.find((d) => d.name?.value === n), needed);
226
+ const queue = [...needed];
227
+ while (queue.length) {
228
+ const name = queue.pop();
229
+ const frag = fragments.get(name);
230
+ if (!frag) continue;
231
+ const nested = /* @__PURE__ */ new Set();
232
+ collectSpreads(frag.def, nested);
233
+ for (const n of nested) if (!needed.has(n)) {
234
+ needed.add(n);
235
+ queue.push(n);
236
+ }
237
+ }
238
+ const extraDefs = [];
239
+ for (const name of needed) {
240
+ if (ownFragments.has(name)) continue;
241
+ const frag = fragments.get(name);
242
+ if (frag) extraDefs.push(frag.def);
243
+ }
244
+ const fullDoc = {
245
+ kind: Kind.DOCUMENT,
246
+ definitions: [...doc.definitions, ...extraDefs]
247
+ };
248
+ let selectsSitePages = false;
249
+ const findSitePages = sitePageSelections(schema, () => selectsSitePages = true);
250
+ const errors = validate(schema, fullDoc, findSitePages ? [...rules, findSitePages] : rules);
251
+ if (errors.length) {
252
+ reporter.panicOnBuild({
253
+ id: "85923",
254
+ context: { sourceMessage: `There was an error in your GraphQL query:\n\n${errors.map((e) => e.message).join("\n")}\n\nFile: ${tag.file}` }
255
+ });
256
+ result.errors++;
257
+ return;
258
+ }
259
+ if (selectsSitePages) readSitePageNodes(`the ${tag.kind} query of ${tag.file}`);
260
+ return extraDefs.length ? `${tag.text}\n${extraDefs.map((d) => print(d)).join("\n")}` : tag.text;
261
+ };
262
+ for (const tag of parsed) {
263
+ if (tag.kind === "fragment") continue;
264
+ if (tag.kind === "page") {
265
+ const file = slash(tag.file);
266
+ if (!components.has(file)) {
267
+ if (tag.exportName && !notedNonPageQueries.has(file)) {
268
+ notedNonPageQueries.add(file);
269
+ reporter.verbose(`No page uses "${file}" as its component: its exported query is not run.`);
270
+ }
271
+ continue;
272
+ }
273
+ if (result.pageQueries.has(file)) {
274
+ reporter.warn(`Multiple page queries found in "${file}". Only the first one is used.`);
275
+ continue;
276
+ }
277
+ const query = compile(tag);
278
+ if (query) result.pageQueries.set(file, {
279
+ query,
280
+ file
281
+ });
282
+ } else {
283
+ const query = compile(tag);
284
+ if (!query) continue;
285
+ const name = tag.operationNames[0] ?? `sq${tag.hash}`;
286
+ result.staticQueries.set(tag.hash, {
287
+ id: `sq--${slash(path.relative(store.getState().program.directory, tag.file)).replace(/[^a-zA-Z0-9-_]/g, "-")}`,
288
+ hash: tag.hash,
289
+ name,
290
+ componentPath: slash(tag.file),
291
+ query,
292
+ rawText: tag.text
293
+ });
294
+ const list = result.staticQueriesByFile.get(slash(tag.file)) ?? [];
295
+ list.push(tag.hash);
296
+ result.staticQueriesByFile.set(slash(tag.file), list);
297
+ }
298
+ }
299
+ const state = store.getState();
300
+ for (const [componentPath] of state.components) {
301
+ const base = componentPath.split("?")[0];
302
+ store.dispatch({
303
+ type: "QUERY_EXTRACTED",
304
+ payload: {
305
+ componentPath,
306
+ query: result.pageQueries.get(base)?.query ?? ""
307
+ }
308
+ });
309
+ }
310
+ for (const id of state.staticQueryComponents.keys()) store.dispatch({
311
+ type: "REMOVE_STATIC_QUERY",
312
+ payload: id
313
+ });
314
+ for (const sq of result.staticQueries.values()) store.dispatch({
315
+ type: "REPLACE_STATIC_QUERY",
316
+ payload: {
317
+ id: sq.hash,
318
+ name: sq.name,
319
+ componentPath: sq.componentPath,
320
+ query: sq.query,
321
+ hash: sq.hash
322
+ }
323
+ });
324
+ return result;
325
+ }
326
+ export { compileFiles, extractAndCompileQueries, runPreprocessSource, warnIfPageQueryIsIgnored };
@@ -0,0 +1,45 @@
1
+ // src/node/query/dependencies.ts
2
+ /**
3
+ * Data dependencies of a query (Gatsby's page dependencies): the ids of the nodes it read and
4
+ * the node types it queried as a whole ("connections" – any added, changed or removed node of
5
+ * such a type can change the result). Used by incremental query running.
6
+ */
7
+ var QueryDependencies = class {
8
+ nodes = /* @__PURE__ */ new Set();
9
+ connections = /* @__PURE__ */ new Set();
10
+ addNode(id) {
11
+ if (typeof id === "string" && id) this.nodes.add(id);
12
+ }
13
+ addConnection(typeName) {
14
+ this.connections.add(typeName);
15
+ }
16
+ merge(other) {
17
+ if (!other || other === this) return;
18
+ for (const id of other.nodes) this.nodes.add(id);
19
+ for (const type of other.connections) this.connections.add(type);
20
+ }
21
+ get size() {
22
+ return this.nodes.size + this.connections.size;
23
+ }
24
+ };
25
+ /** connection on every node type (e.g. `getAllNodes()` without a type) */
26
+ const ALL_TYPES = "*";
27
+ /** dependencies of the queries running right now, by page path (Gatsby's path based APIs) */
28
+ const running = /* @__PURE__ */ new Map();
29
+ function registerRunningQuery(path, dependencies) {
30
+ running.set(path, dependencies);
31
+ }
32
+ function unregisterRunningQuery(path, dependencies) {
33
+ if (running.get(path) === dependencies) running.delete(path);
34
+ }
35
+ /**
36
+ * `getNodeAndSavePathDependency(id, path)` and `actions.createPageDependency({ path, nodeId,
37
+ * connection })`: record a dependency of the query running for `path`.
38
+ */
39
+ function recordPathDependency(path, dependency) {
40
+ const dependencies = path ? running.get(path) : void 0;
41
+ if (!dependencies) return;
42
+ if (dependency.nodeId) dependencies.addNode(dependency.nodeId);
43
+ if (dependency.connection) dependencies.addConnection(dependency.connection);
44
+ }
45
+ export { ALL_TYPES, QueryDependencies, recordPathDependency, registerRunningQuery, unregisterRunningQuery };