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,231 @@
1
+ import { Kind, introspectionFromSchema, isScalarType, print, printSchema } 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 { slash } from "../utils/paths.js";
6
+ import { isMainThread } from "node:worker_threads";
7
+ import path from "node:path";
8
+ import fs from "node:fs";
9
+ // src/node/query/graphql-env.ts
10
+ /**
11
+ * The global interface the generated declaration file augments with the site's schema and
12
+ * fragments. `types/index.d.ts` reads it to type `graphql()` documents with gql.tada.
13
+ */
14
+ const GRAPHQL_ENV_INTERFACE = "GatsbyGraphQLTypes";
15
+ /** where the declaration file goes by default (not gql.tada's own `graphql-env.d.ts`) */
16
+ const DEFAULT_GRAPHQL_ENV_PATH = "src/gatsby-graphql-env.d.ts";
17
+ /** in the generated file: files without it are not overwritten */
18
+ const MARKER = "// Generated by goatly from the site's GraphQL schema and fragments";
19
+ const HEADER = `/* eslint-disable */
20
+ // biome-ignore-all lint: generated file
21
+ // biome-ignore-all format: generated file
22
+ /* prettier-ignore */
23
+ ${MARKER} – do not edit.
24
+ // It types \`graphql()\` documents, \`QueryResult<"Name">\` and \`FragmentResult<"Name">\` from "gatsby"
25
+ // with gql.tada (see the goatly README).
26
+ `;
27
+ /** gql.tada's preprocessed schema type of a schema, cached per schema object */
28
+ const schemaTypes = /* @__PURE__ */ new WeakMap();
29
+ /** the last one by its printed schema (develop builds a new schema object on each data change) */
30
+ let lastSchemaType;
31
+ const byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
32
+ async function schemaType(schema) {
33
+ let text = schemaTypes.get(schema);
34
+ if (text !== void 0) return text;
35
+ const printed = printSchema(schema);
36
+ if (lastSchemaType?.printed === printed) text = lastSchemaType.text;
37
+ else {
38
+ const { preprocessIntrospection } = await import("./gql-tada-introspection.js");
39
+ const introspection = introspectionFromSchema(schema, { descriptions: false });
40
+ for (const type of introspection.__schema.types) {
41
+ type.inputFields?.sort(byName);
42
+ type.enumValues?.sort(byName);
43
+ }
44
+ text = preprocessIntrospection(introspection);
45
+ lastSchemaType = {
46
+ printed,
47
+ text
48
+ };
49
+ }
50
+ schemaTypes.set(schema, text);
51
+ return text;
52
+ }
53
+ function collectSpreads(node, out) {
54
+ if (!node || typeof node !== "object") return;
55
+ if (Array.isArray(node)) {
56
+ for (const n of node) collectSpreads(n, out);
57
+ return;
58
+ }
59
+ if (node.kind === Kind.FRAGMENT_SPREAD) out.add(node.name.value);
60
+ for (const key of ["selectionSet", "selections"]) if (node[key]) collectSpreads(node[key], out);
61
+ }
62
+ /**
63
+ * Fragment entries `Name: readonly [source, ...spread fragment names]`. Fragments that are part of
64
+ * a cycle, or spread a fragment that does not exist (both are GraphQL validation errors reported by
65
+ * query compilation), are left out: gql.tada resolves the spreads recursively.
66
+ */
67
+ function fragmentEntries(fragments) {
68
+ const deps = /* @__PURE__ */ new Map();
69
+ for (const [name, { def }] of fragments) {
70
+ const spreads = /* @__PURE__ */ new Set();
71
+ collectSpreads(def, spreads);
72
+ deps.set(name, [...spreads].sort());
73
+ }
74
+ const valid = /* @__PURE__ */ new Map();
75
+ const check = (name, visiting) => {
76
+ const known = valid.get(name);
77
+ if (known !== void 0) return known;
78
+ if (!deps.has(name) || visiting.has(name)) return false;
79
+ visiting.add(name);
80
+ const ok = deps.get(name).every((dep) => check(dep, visiting));
81
+ visiting.delete(name);
82
+ valid.set(name, ok);
83
+ return ok;
84
+ };
85
+ const entries = [];
86
+ for (const name of [...fragments.keys()].sort()) {
87
+ if (!check(name, /* @__PURE__ */ new Set())) continue;
88
+ const tuple = [print(fragments.get(name).def), ...deps.get(name)].map((s) => JSON.stringify(s)).join(", ");
89
+ entries.push(entry(name, `readonly [${tuple}]`));
90
+ }
91
+ return entries;
92
+ }
93
+ const entry = (name, value) => ` ${JSON.stringify(name)}: ${value};`;
94
+ const block = (name, entries) => ` ${name}: {${entries.length ? `\n${entries.join("\n")}\n ` : ""}};`;
95
+ /**
96
+ * The declaration file that registers the site's schema (gql.tada's preprocessed introspection),
97
+ * TypeScript types of custom scalars (source text by scalar name), all fragments (global by name,
98
+ * like in Gatsby) and the named queries (printed, by name) for `graphql()` documents and the
99
+ * name-keyed types. A global script without imports, so that it works whatever name goatly
100
+ * is installed under.
101
+ */
102
+ async function renderGraphQLEnv(schema, fragments, scalars = {}, queries = /* @__PURE__ */ new Map()) {
103
+ const indented = (await schemaType(schema)).replace(/\n/g, "\n ");
104
+ const scalarEntries = Object.keys(scalars).sort().map((name) => entry(name, scalars[name]));
105
+ const queryEntries = [...queries.keys()].sort().filter((name) => queries.get(name) != null).map((name) => entry(name, JSON.stringify(queries.get(name))));
106
+ return `${HEADER}
107
+ interface ${GRAPHQL_ENV_INTERFACE} {
108
+ introspection: ${indented};
109
+ ${block("scalars", scalarEntries)}
110
+ ${block("fragments", fragmentEntries(fragments))}
111
+ ${block("queries", queryEntries)}
112
+ }
113
+ `;
114
+ }
115
+ /** Whether `file` was written by goatly (or does not exist). */
116
+ function isGeneratedFile(file) {
117
+ try {
118
+ return fs.readFileSync(file, "utf8").slice(0, 400).includes(MARKER);
119
+ } catch {
120
+ return !fs.existsSync(file);
121
+ }
122
+ }
123
+ /**
124
+ * Writes the file when its content changed, but never over a file goatly did not write.
125
+ * Returns what happened.
126
+ */
127
+ function writeGraphQLEnv(file, content) {
128
+ let existing;
129
+ try {
130
+ existing = fs.readFileSync(file, "utf8");
131
+ } catch {}
132
+ if (existing === content) return "unchanged";
133
+ if (existing !== void 0 && !existing.slice(0, 400).includes(MARKER)) return "not-generated";
134
+ fs.mkdirSync(path.dirname(file), { recursive: true });
135
+ fs.writeFileSync(file, content);
136
+ return "written";
137
+ }
138
+ /**
139
+ * Where the declaration file of the site goes (absolute), or `undefined` when it is turned off. By
140
+ * default, for TypeScript sites (a tsconfig.json in the site directory); see `shouldGenerate`.
141
+ */
142
+ function graphqlEnvFile(siteDir, option) {
143
+ if (option === false) return void 0;
144
+ if (option === void 0 && !fs.existsSync(path.join(siteDir, "tsconfig.json"))) return void 0;
145
+ const typesOutputPath = typeof option === "object" && option.typesOutputPath || "src/gatsby-graphql-env.d.ts";
146
+ return path.resolve(siteDir, typesOutputPath);
147
+ }
148
+ /**
149
+ * Whether to write the declaration file: when configured explicitly, otherwise once the site uses
150
+ * `graphql()` calls or the name-keyed types (`QueryResult<"Name">`, …), or the file exists already.
151
+ * Sites with only Gatsby's tags get no new file.
152
+ */
153
+ function shouldGenerate(file, option, usesGraphqlTypes) {
154
+ return option !== void 0 || usesGraphqlTypes || fs.existsSync(file) && isGeneratedFile(file);
155
+ }
156
+ /** Whether a package is installed for the site (TypeScript resolves type imports in its files). */
157
+ function isInstalled(siteDir, name) {
158
+ for (let dir = siteDir;; dir = path.dirname(dir)) {
159
+ if (fs.existsSync(path.join(dir, "node_modules", name, "package.json"))) return true;
160
+ if (path.dirname(dir) === dir) return false;
161
+ }
162
+ }
163
+ const SCALARS_WITH_DEFAULTS = /* @__PURE__ */ new Set([
164
+ "String",
165
+ "Int",
166
+ "Float",
167
+ "Boolean",
168
+ "ID",
169
+ "Date",
170
+ "JSON"
171
+ ]);
172
+ /**
173
+ * TypeScript types of the custom scalars of the schema (`Date` and `JSON` have defaults in the
174
+ * types): gatsby-plugin-image's `GatsbyImageData` when it is installed, `any` otherwise (as in
175
+ * Gatsby's typegen). `GatsbyGraphQLScalars` overrides them.
176
+ */
177
+ function customScalars(schema, siteDir) {
178
+ const scalars = {};
179
+ for (const type of Object.values(schema.getTypeMap())) {
180
+ if (!isScalarType(type) || SCALARS_WITH_DEFAULTS.has(type.name)) continue;
181
+ scalars[type.name] = type.name === "GatsbyImageData" && isInstalled(siteDir, "gatsby-plugin-image") ? `import("gatsby-plugin-image").IGatsbyImageData` : "any";
182
+ }
183
+ return scalars;
184
+ }
185
+ const warned = /* @__PURE__ */ new Set();
186
+ /**
187
+ * Generates the declaration file after query extraction (main thread: bootstrap, and develop when
188
+ * files or data change). Writes only when the schema or the fragments changed.
189
+ */
190
+ async function updateGraphQLEnv({ fragments, queries, usesGraphqlTypes }) {
191
+ if (!isMainThread) return;
192
+ const state = store.getState();
193
+ const siteDir = state.program.directory;
194
+ const option = state.config.gqlTada;
195
+ const file = graphqlEnvFile(siteDir, option);
196
+ if (option === false) {
197
+ const previous = path.resolve(siteDir, DEFAULT_GRAPHQL_ENV_PATH);
198
+ if (fs.existsSync(previous) && isGeneratedFile(previous) && !warned.has(previous)) {
199
+ warned.add(previous);
200
+ reporter.warn(`Delete "${DEFAULT_GRAPHQL_ENV_PATH}": the GraphQL types are turned off (gqlTada: false), but the file goatly generated before still types graphql() documents.`);
201
+ }
202
+ }
203
+ if (!file || !shouldGenerate(file, option, usesGraphqlTypes)) return;
204
+ const relative = slash(path.relative(siteDir, file));
205
+ try {
206
+ const schema = getSchema();
207
+ const result = writeGraphQLEnv(file, await renderGraphQLEnv(schema, fragments, customScalars(schema, siteDir), queries));
208
+ for (const [name, query] of queries) {
209
+ if (query !== null || warned.has(`query ${name}`)) continue;
210
+ warned.add(`query ${name}`);
211
+ reporter.warn(`Different queries are named "${name}": QueryResult<"${name}"> and QueryVariables<"${name}"> are not available. Give the queries distinct names.`);
212
+ }
213
+ if (result === "written") reporter.verbose(`Wrote GraphQL types to ${relative}`);
214
+ if (result === "not-generated" && !warned.has(file)) {
215
+ warned.add(file);
216
+ reporter.warn(`"${relative}" was not written by goatly, so it is not overwritten with the GraphQL types of graphql() queries. Set another path with gqlTada: { typesOutputPath: "..." } in gatsby-config (or gqlTada: false to turn them off).`);
217
+ }
218
+ const previous = path.resolve(siteDir, DEFAULT_GRAPHQL_ENV_PATH);
219
+ if (previous !== file && fs.existsSync(previous) && isGeneratedFile(previous) && !warned.has(previous)) {
220
+ warned.add(previous);
221
+ reporter.warn(`Delete "${DEFAULT_GRAPHQL_ENV_PATH}": goatly writes the GraphQL types to "${relative}" now, and the old file would conflict with it.`);
222
+ }
223
+ } catch (e) {
224
+ const message = `Could not write the GraphQL types for graphql() to "${relative}": ${e.message}`;
225
+ if (!warned.has(message)) {
226
+ warned.add(message);
227
+ reporter.warn(message);
228
+ }
229
+ }
230
+ }
231
+ export { DEFAULT_GRAPHQL_ENV_PATH, GRAPHQL_ENV_INTERFACE, graphqlEnvFile, isGeneratedFile, renderGraphQLEnv, shouldGenerate, updateGraphQLEnv, writeGraphQLEnv };
@@ -0,0 +1,79 @@
1
+ import { KnownFragmentNamesRule, NoUnusedFragmentsRule, parse, specifiedRules, validate } from "../gql.js";
2
+ import { createGraphQLContext, getSchema } from "../schema/index.js";
3
+ import { executeQuery } from "./execute.js";
4
+ import { registerRunningQuery, unregisterRunningQuery } from "./dependencies.js";
5
+ // src/node/query/graphql-runner.ts
6
+ const documentCache = /* @__PURE__ */ new Map();
7
+ const rules = specifiedRules.filter((r) => r !== NoUnusedFragmentsRule);
8
+ function clearDocumentCache() {
9
+ documentCache.clear();
10
+ }
11
+ function prepare(query, schema) {
12
+ const cached = documentCache.get(query);
13
+ if (cached && cached.schema === schema) return cached;
14
+ let document;
15
+ try {
16
+ document = parse(query);
17
+ } catch (e) {
18
+ const entry = {
19
+ schema,
20
+ document: {
21
+ kind: "Document",
22
+ definitions: []
23
+ },
24
+ errors: [e]
25
+ };
26
+ documentCache.set(query, entry);
27
+ return entry;
28
+ }
29
+ const errors = validate(schema, document, rules);
30
+ const entry = {
31
+ schema,
32
+ document,
33
+ errors
34
+ };
35
+ documentCache.set(query, entry);
36
+ return entry;
37
+ }
38
+ /** the parsed and validated document of a query (cached, as runGraphQL uses it) */
39
+ function preparedDocument(query, schema = getSchema()) {
40
+ return prepare(query, schema);
41
+ }
42
+ /**
43
+ * Runs a GraphQL query against the current schema. Documents are parsed and
44
+ * validated once and cached (page templates execute the same query many times).
45
+ */
46
+ /**
47
+ * Runs a GraphQL query against the site's schema. With `dependencies` the nodes and node types
48
+ * the query reads are recorded (incremental query running).
49
+ */
50
+ async function runGraphQL(query, variables = {}, path, dependencies, options) {
51
+ const schema = getSchema();
52
+ let document;
53
+ if (typeof query !== "string") document = query;
54
+ else {
55
+ const prepared = prepare(query, schema);
56
+ if (prepared.errors.length) return { errors: prepared.errors };
57
+ document = prepared.document;
58
+ }
59
+ const track = dependencies && path ? path : void 0;
60
+ if (track) registerRunningQuery(track, dependencies);
61
+ try {
62
+ return await executeQuery({
63
+ schema,
64
+ document,
65
+ variableValues: variables,
66
+ contextValue: {
67
+ ...variables,
68
+ ...createGraphQLContext(path, dependencies)
69
+ }
70
+ }, options);
71
+ } finally {
72
+ if (track) unregisterRunningQuery(track, dependencies);
73
+ }
74
+ }
75
+ /** The `graphql` helper passed to createPages / onPostBuild etc. */
76
+ function graphqlForApis(query, variables) {
77
+ return runGraphQL(query, variables ?? {}, void 0);
78
+ }
79
+ export { KnownFragmentNamesRule, clearDocumentCache, graphqlForApis, preparedDocument, runGraphQL };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,133 @@
1
+ import { createSelfContainedNodeCodec } from "../datastore/codec.js";
2
+ import { clearChangedNodeTypes, getChangedNodeTypes, getNodeChangeCount, getNodeChanges, getStoreEpoch, getTypesTick, resetNodeChanges, takeNodeChanges } from "./node-changes.js";
3
+ import { deepMerge, reduce } from "./reducers.js";
4
+ import { initialState } from "./state.js";
5
+ import { EventEmitter } from "node:events";
6
+ // src/node/redux/index.ts
7
+ let state = initialState();
8
+ /**
9
+ * Internal event emitter – every dispatched action is also emitted under its type,
10
+ * exactly like Gatsby's `emitter` so plugins listening for e.g. `CREATE_PAGE`,
11
+ * `DELETE_PAGE` or `BOOTSTRAP_FINISHED` keep working.
12
+ */
13
+ var GatsbyEmitter = class extends EventEmitter {};
14
+ const emitter = new GatsbyEmitter();
15
+ emitter.setMaxListeners(1e3);
16
+ /** listeners of goatly itself, which stay attached when the store is reset */
17
+ const internalActionListeners = [];
18
+ /**
19
+ * Listens to actions of a type for as long as the process runs: unlike `emitter.on`, the listener
20
+ * stays attached when the store is reset (`resetStore` detaches the listeners plugins added).
21
+ */
22
+ function onAction(type, listener) {
23
+ internalActionListeners.push([type, listener]);
24
+ emitter.on(type, listener);
25
+ }
26
+ /**
27
+ * Copied on change, never changed in place: a dispatch notifies the listeners subscribed when it
28
+ * started, like redux (also when a listener subscribes or unsubscribes during the dispatch).
29
+ */
30
+ let listeners = [];
31
+ function assertAction(action) {
32
+ if (action === null || typeof action !== "object") throw new TypeError(`Actions must be objects, arrays of actions or functions, got ${action}`);
33
+ if (typeof action.type !== "string") throw new TypeError(`Actions must have a string "type" property, got ${JSON.stringify(action.type)}`);
34
+ }
35
+ function dispatchOne(action) {
36
+ assertAction(action);
37
+ reduce(state, action);
38
+ emitter.emit(action.type, action.type === "ADD_CHILD_NODE_TO_PARENT_NODE" && action.deferDigest === true ? listenerAction(action) : action);
39
+ const current = listeners;
40
+ for (let i = 0; i < current.length; i++) current[i]();
41
+ }
42
+ /**
43
+ * The action listeners get for an action whose payload is the datastore's working copy
44
+ * (`deferDigest`, from createParentChildLink): its payload is the node as of this action, a separate
45
+ * object made when it is first read, never the working copy itself (that one changes with later
46
+ * links, and changing it would change the stored node).
47
+ */
48
+ function listenerAction(action) {
49
+ const { payload: work, deferDigest: _, ...rest } = action;
50
+ const linked = work.children.length;
51
+ let node;
52
+ return Object.defineProperty(rest, "payload", {
53
+ enumerable: true,
54
+ configurable: true,
55
+ get: () => node ??= snapshotOf(work, linked),
56
+ set: (value) => {
57
+ Object.defineProperty(rest, "payload", {
58
+ value,
59
+ writable: true,
60
+ enumerable: true,
61
+ configurable: true
62
+ });
63
+ }
64
+ });
65
+ }
66
+ const snapshotCodec = createSelfContainedNodeCodec();
67
+ /**
68
+ * A copy of a working copy as of an action, decoded like a read. Its children are the first
69
+ * `linked` ids of the working copy's (they only grow, by push), copied when they are read: listeners
70
+ * that look at other fields (e.g. `internal.type`) don't copy a long array on every link.
71
+ */
72
+ function snapshotOf(work, linked) {
73
+ const node = snapshotCodec.unpack(snapshotCodec.pack({
74
+ ...work,
75
+ children: null
76
+ }));
77
+ let children;
78
+ Object.defineProperty(node, "children", {
79
+ enumerable: true,
80
+ configurable: true,
81
+ get: () => children ??= work.children.slice(0, linked),
82
+ set: (value) => {
83
+ children = value;
84
+ }
85
+ });
86
+ return node;
87
+ }
88
+ /**
89
+ * A tiny redux compatible store. Supports dispatching arrays of actions and thunks,
90
+ * like Gatsby's store (which uses redux-thunk + multi middleware).
91
+ */
92
+ const dispatch = ((action) => {
93
+ if (typeof action === "function") return action(dispatch, getState);
94
+ if (Array.isArray(action)) {
95
+ for (const a of action) dispatch(a);
96
+ return action;
97
+ }
98
+ dispatchOne(action);
99
+ return action;
100
+ });
101
+ function getState() {
102
+ return state;
103
+ }
104
+ const store = {
105
+ getState,
106
+ dispatch,
107
+ subscribe(listener) {
108
+ if (typeof listener !== "function") throw new TypeError(`Expected the listener to be a function, got ${typeof listener}`);
109
+ const entry = () => listener();
110
+ listeners = [...listeners, entry];
111
+ let subscribed = true;
112
+ return () => {
113
+ if (!subscribed) return;
114
+ subscribed = false;
115
+ listeners = listeners.filter((l) => l !== entry);
116
+ };
117
+ },
118
+ replaceReducer() {
119
+ throw new Error("replaceReducer is not supported by goatly");
120
+ }
121
+ };
122
+ /**
123
+ * A fresh state, as when the process started. Listeners plugins added (`emitter.on`,
124
+ * `store.subscribe`) are detached; those of goatly itself (`onAction`) stay.
125
+ */
126
+ function resetStore() {
127
+ state = initialState();
128
+ resetNodeChanges();
129
+ emitter.removeAllListeners();
130
+ for (const [type, listener] of internalActionListeners) emitter.on(type, listener);
131
+ listeners = [];
132
+ }
133
+ export { clearChangedNodeTypes, deepMerge, emitter, getChangedNodeTypes, getNodeChangeCount, getNodeChanges, getStoreEpoch, getTypesTick, onAction, resetStore, store, takeNodeChanges };
@@ -0,0 +1,128 @@
1
+ import { nodeDigest } from "../build/incremental.js";
2
+ // src/node/redux/node-changes.ts
3
+ /**
4
+ * Bookkeeping of node changes, kept up to date by the node reducers (before any listener runs):
5
+ * the digests incremental builds need, the node types schema inference must look at again and the
6
+ * per-type change ticks of the query engine's caches.
7
+ */
8
+ /**
9
+ * Nodes changed by actions since the process started: id → [digest, type] (null: deleted).
10
+ * Incremental query running applies these to the previous build's node digests instead of
11
+ * reading every node again (for lazy datastores that means not deserializing all nodes).
12
+ */
13
+ let nodeChanges = /* @__PURE__ */ new Map();
14
+ function getNodeChanges() {
15
+ resolveDeferredDigests(0);
16
+ return nodeChanges;
17
+ }
18
+ /** the changes recorded so far; later changes are recorded from scratch (frees the entries) */
19
+ function takeNodeChanges() {
20
+ resolveDeferredDigests(0);
21
+ const taken = nodeChanges;
22
+ nodeChanges = /* @__PURE__ */ new Map();
23
+ return taken;
24
+ }
25
+ /**
26
+ * Node types with created, changed or deleted nodes since the last schema build: inference
27
+ * results of all other types are still valid. `storeEpoch` changes when the store is reset.
28
+ */
29
+ const changedTypes = /* @__PURE__ */ new Set();
30
+ let storeEpoch = 0;
31
+ /** number of node changes since the process started (monotonic) */
32
+ let nodeChangeCount = 0;
33
+ function getNodeChangeCount() {
34
+ return nodeChangeCount;
35
+ }
36
+ function getChangedNodeTypes() {
37
+ return changedTypes;
38
+ }
39
+ function clearChangedNodeTypes() {
40
+ changedTypes.clear();
41
+ }
42
+ function getStoreEpoch() {
43
+ return storeEpoch;
44
+ }
45
+ /**
46
+ * Change ticks per node type for the query engine's caches of raw node values (id lists, value
47
+ * indexes, projections): the SitePage node createPage creates between two queries of createPages
48
+ * leaves the caches of all other types valid. One counter for all types that never goes back (also
49
+ * not on a store reset), so a tick never repeats a cache stamp of other data.
50
+ */
51
+ let typeTick = 0;
52
+ const typeTicks = /* @__PURE__ */ new Map();
53
+ /** changes of unknown type (and store resets) count for every type */
54
+ let allTypesTick = 0;
55
+ function bumpType(type) {
56
+ typeTicks.set(type, ++typeTick);
57
+ }
58
+ function bumpAllTypes() {
59
+ allTypesTick = ++typeTick;
60
+ }
61
+ /** the latest change tick of nodes of these types */
62
+ function getTypesTick(typeNames) {
63
+ let tick = allTypesTick;
64
+ for (const type of typeNames) {
65
+ const t = typeTicks.get(type);
66
+ if (t !== void 0 && t > tick) tick = t;
67
+ }
68
+ return tick;
69
+ }
70
+ /**
71
+ * Nodes whose digest is computed later: the datastore's working copies that actions change in place
72
+ * (`getNodeForUpdate`), which nothing else changes – a node that gets many links or fields is
73
+ * digested once. The most recently changed come last; at most MAX_DEFERRED are kept.
74
+ */
75
+ const deferredDigests = /* @__PURE__ */ new Map();
76
+ const MAX_DEFERRED = 1e3;
77
+ function resolveDeferredDigests(keep) {
78
+ for (const [id, node] of deferredDigests) {
79
+ if (deferredDigests.size <= keep) break;
80
+ deferredDigests.delete(id);
81
+ nodeChanges.set(id, [nodeDigest(node), node.internal.type]);
82
+ }
83
+ }
84
+ /**
85
+ * A node was created or changed. `previousType` is its stored type before the change (a retyped
86
+ * node leaves its old type too); `deferDigest`: the node is the datastore's working copy.
87
+ */
88
+ function recordNodeChange(node, previousType, deferDigest = false) {
89
+ if (node?.id && node.internal?.type) {
90
+ deferredDigests.delete(node.id);
91
+ if (deferDigest) {
92
+ deferredDigests.set(node.id, node);
93
+ if (deferredDigests.size > MAX_DEFERRED) resolveDeferredDigests(MAX_DEFERRED);
94
+ } else nodeChanges.set(node.id, [nodeDigest(node), node.internal.type]);
95
+ changedTypes.add(node.internal.type);
96
+ nodeChangeCount++;
97
+ bumpType(node.internal.type);
98
+ } else bumpAllTypes();
99
+ if (previousType !== void 0 && previousType !== node?.internal?.type) {
100
+ changedTypes.add(previousType);
101
+ bumpType(previousType);
102
+ }
103
+ }
104
+ /** A node was deleted. `storedType`: its type in the datastore (the payload may be a copy). */
105
+ function recordNodeDelete(node, storedType) {
106
+ deferredDigests.delete(node.id);
107
+ nodeChanges.set(node.id, null);
108
+ nodeChangeCount++;
109
+ const type = node.internal?.type;
110
+ if (type) {
111
+ changedTypes.add(type);
112
+ bumpType(type);
113
+ }
114
+ if (storedType !== void 0 && storedType !== type) {
115
+ changedTypes.add(storedType);
116
+ bumpType(storedType);
117
+ } else if (!type) bumpAllTypes();
118
+ }
119
+ /** the store was reset: every node may have changed */
120
+ function resetNodeChanges() {
121
+ nodeChanges.clear();
122
+ deferredDigests.clear();
123
+ changedTypes.clear();
124
+ typeTicks.clear();
125
+ bumpAllTypes();
126
+ storeEpoch++;
127
+ }
128
+ export { clearChangedNodeTypes, getChangedNodeTypes, getNodeChangeCount, getNodeChanges, getStoreEpoch, getTypesTick, recordNodeChange, recordNodeDelete, resetNodeChanges, takeNodeChanges };