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,372 @@
1
+ import { murmurhash } from "../utils/murmurhash.js";
2
+ import { slash } from "../utils/paths.js";
3
+ import { parseSync } from "../utils/parser.js";
4
+ import { sourceLang } from "../plugins/static-exports.js";
5
+ import path from "node:path";
6
+ import fs from "node:fs";
7
+ import { glob } from "tinyglobby";
8
+ // src/node/query/extract.ts
9
+ /** the types of "gatsby" that read the queries and fragments of the generated declaration file */
10
+ const REGISTRY_TYPES = /* @__PURE__ */ new Set([
11
+ "QueryResult",
12
+ "QueryVariables",
13
+ "FragmentResult"
14
+ ]);
15
+ const REGISTRY_PATTERN = /\b(QueryResult|QueryVariables|FragmentResult)\b/;
16
+ const GATSBY_MODULES = /* @__PURE__ */ new Set(["gatsby", "goatly"]);
17
+ /** Gatsby-compatible static query hash */
18
+ function hashQuery(text) {
19
+ return String(murmurhash(text, 0));
20
+ }
21
+ function walk(node, visit, parent = null) {
22
+ if (!node || typeof node !== "object") return;
23
+ if (Array.isArray(node)) {
24
+ for (const child of node) walk(child, visit, parent);
25
+ return;
26
+ }
27
+ if (typeof node.type !== "string") return;
28
+ visit(node, parent);
29
+ for (const key in node) {
30
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range") continue;
31
+ const value = node[key];
32
+ if (value && typeof value === "object") walk(value, visit, node);
33
+ }
34
+ }
35
+ function tagName(tag) {
36
+ if (tag?.type === "Identifier") return tag.name;
37
+ if ((tag?.type === "MemberExpression" || tag?.type === "StaticMemberExpression") && tag.property?.name === "graphql") return "graphql";
38
+ }
39
+ function quickNames(text) {
40
+ const operationNames = [];
41
+ const fragmentNames = [];
42
+ for (const m of text.matchAll(/\b(query|fragment)\s+([_A-Za-z][_0-9A-Za-z]*)/g)) if (m[1] === "query") operationNames.push(m[2]);
43
+ else fragmentNames.push(m[2]);
44
+ return {
45
+ operationNames,
46
+ fragmentNames
47
+ };
48
+ }
49
+ /** TypeScript-only wrappers of an expression (`graphql(...) as X`, `(graphql(...))!`, …) */
50
+ const EXPRESSION_WRAPPERS = /* @__PURE__ */ new Set([
51
+ "TSAsExpression",
52
+ "TSSatisfiesExpression",
53
+ "TSNonNullExpression",
54
+ "TSTypeAssertion",
55
+ "TSInstantiationExpression",
56
+ "ParenthesizedExpression",
57
+ "ChainExpression"
58
+ ]);
59
+ function unwrapExpression(node) {
60
+ while (node && EXPRESSION_WRAPPERS.has(node.type)) node = node.expression;
61
+ return node;
62
+ }
63
+ /** The names a binding pattern (`a`, `{ a, b: c }`, `[a, ...b]`, `a = 1`) declares. */
64
+ function patternNames(pattern, out = []) {
65
+ if (!pattern || typeof pattern !== "object") return out;
66
+ switch (pattern.type) {
67
+ case "Identifier":
68
+ out.push(pattern.name);
69
+ break;
70
+ case "ObjectPattern":
71
+ for (const prop of pattern.properties ?? []) patternNames(prop.type === "RestElement" ? prop.argument : prop.value, out);
72
+ break;
73
+ case "ArrayPattern":
74
+ for (const el of pattern.elements ?? []) patternNames(el, out);
75
+ break;
76
+ case "AssignmentPattern":
77
+ patternNames(pattern.left, out);
78
+ break;
79
+ case "RestElement":
80
+ patternNames(pattern.argument, out);
81
+ break;
82
+ case "TSParameterProperty": patternNames(pattern.parameter, out);
83
+ }
84
+ return out;
85
+ }
86
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
87
+ "FunctionDeclaration",
88
+ "FunctionExpression",
89
+ "ArrowFunctionExpression"
90
+ ]);
91
+ /** nodes with a scope of their own for `let`, `const`, `class` and (in modules) functions */
92
+ const BLOCK_SCOPES = /* @__PURE__ */ new Set([
93
+ "BlockStatement",
94
+ "StaticBlock",
95
+ "ForStatement",
96
+ "ForInStatement",
97
+ "ForOfStatement",
98
+ "SwitchStatement",
99
+ "CatchClause",
100
+ "ClassBody",
101
+ "TSModuleBlock"
102
+ ]);
103
+ /**
104
+ * Source ranges of the scopes that declare one of `names` themselves (lexical scopes: functions,
105
+ * blocks, `for` heads, catch clauses, …; `var` belongs to the function). A `graphql(...)` call inside
106
+ * such a range calls that binding, not the import.
107
+ */
108
+ function shadowingRanges(program, names) {
109
+ const ranges = [];
110
+ /** the scopes around the visited node; `fn` marks function scopes (and the program) */
111
+ const scopes = [{
112
+ node: program,
113
+ fn: true
114
+ }];
115
+ const declare = (declared, functionScope = false) => {
116
+ if (!declared.some((n) => names.has(n))) return;
117
+ let i = scopes.length - 1;
118
+ if (functionScope) while (!scopes[i].fn) i--;
119
+ if (i > 0) ranges.push([scopes[i].node.start, scopes[i].node.end]);
120
+ };
121
+ const visit = (node, parent) => {
122
+ if (!node || typeof node !== "object") return;
123
+ if (Array.isArray(node)) {
124
+ for (const child of node) visit(child, parent);
125
+ return;
126
+ }
127
+ if (typeof node.type !== "string") return;
128
+ if (node.type === "VariableDeclaration") for (const d of node.declarations ?? []) declare(patternNames(d.id), node.kind === "var");
129
+ if ((node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") && node.id) declare([node.id.name]);
130
+ const isFunction = FUNCTION_TYPES.has(node.type);
131
+ const isScope = isFunction || node.type === "ClassExpression" || BLOCK_SCOPES.has(node.type) && !(FUNCTION_TYPES.has(parent?.type) && parent.body === node);
132
+ if (isScope) {
133
+ scopes.push({
134
+ node,
135
+ fn: isFunction || node.type === "StaticBlock" || node.type === "TSModuleBlock"
136
+ });
137
+ if (isFunction) {
138
+ declare((node.params ?? []).flatMap((param) => patternNames(param)));
139
+ if (node.type === "FunctionExpression" && node.id) declare([node.id.name]);
140
+ }
141
+ if (node.type === "CatchClause" && node.param) declare(patternNames(node.param));
142
+ if (node.type === "ClassExpression" && node.id) declare([node.id.name]);
143
+ }
144
+ for (const key in node) {
145
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range") continue;
146
+ const value = node[key];
147
+ if (value && typeof value === "object") visit(value, node);
148
+ }
149
+ if (isScope) scopes.pop();
150
+ };
151
+ visit(program, null);
152
+ return ranges;
153
+ }
154
+ /**
155
+ * Extracts the `graphql` documents of a JS/TS module using oxc: tagged templates (`graphql\`...\``,
156
+ * Gatsby's form) and calls (`graphql(\`...\`, [fragments])`, gql.tada's form, which TypeScript can
157
+ * type). Classification follows Gatsby: documents passed to `useStaticQuery()` /
158
+ * `<StaticQuery query>` are static queries, other documents containing an operation are page
159
+ * queries, and fragment-only documents are fragments.
160
+ *
161
+ * The call form is only recognized for a `graphql` imported from "gatsby" / "goatly" (or
162
+ * called on a namespace or default import of them), never for the global `graphql` Gatsby also
163
+ * accepts for tags: a `graphql()` function of another library (e.g. gql.tada's own, for a client
164
+ * of another GraphQL API) stays untouched.
165
+ */
166
+ function extractFromSource(file, code) {
167
+ if (!code.includes("graphql") && !REGISTRY_PATTERN.test(code)) return {
168
+ file,
169
+ tags: []
170
+ };
171
+ let program;
172
+ try {
173
+ const result = parseSync(file, code, { lang: sourceLang(file) });
174
+ if (result.errors?.length && !result.program?.body?.length) return {
175
+ file,
176
+ tags: [],
177
+ error: new Error(result.errors.map((e) => e.message).join("\n"))
178
+ };
179
+ program = result.program;
180
+ } catch (e) {
181
+ return {
182
+ file,
183
+ tags: [],
184
+ error: e
185
+ };
186
+ }
187
+ let graphqlImportedElsewhere = false;
188
+ const tagNames = /* @__PURE__ */ new Set();
189
+ const callNames = /* @__PURE__ */ new Set();
190
+ const moduleNames = /* @__PURE__ */ new Set();
191
+ /** local names of gatsby's useStaticQuery and StaticQuery (they may be aliased) */
192
+ const hookNames = /* @__PURE__ */ new Set(["useStaticQuery"]);
193
+ const componentNames = /* @__PURE__ */ new Set(["StaticQuery"]);
194
+ let usesRegistry = false;
195
+ for (const stmt of program.body) {
196
+ if (stmt.type !== "ImportDeclaration") continue;
197
+ const fromGatsby = GATSBY_MODULES.has(stmt.source.value);
198
+ for (const spec of stmt.specifiers ?? []) {
199
+ const importedName = spec.imported?.name ?? spec.imported?.value;
200
+ if (fromGatsby && REGISTRY_TYPES.has(importedName)) usesRegistry = true;
201
+ if (stmt.importKind === "type" || spec.importKind === "type") continue;
202
+ if (fromGatsby && importedName === "useStaticQuery") hookNames.add(spec.local.name);
203
+ if (fromGatsby && importedName === "StaticQuery") componentNames.add(spec.local.name);
204
+ if (fromGatsby && (spec.type === "ImportNamespaceSpecifier" || spec.type === "ImportDefaultSpecifier")) {
205
+ moduleNames.add(spec.local.name);
206
+ continue;
207
+ }
208
+ if ((spec.imported?.name ?? spec.imported?.value) === "graphql") {
209
+ if (fromGatsby) {
210
+ tagNames.add(spec.local.name);
211
+ callNames.add(spec.local.name);
212
+ } else if (spec.local.name === "graphql") graphqlImportedElsewhere = true;
213
+ }
214
+ }
215
+ }
216
+ if (!graphqlImportedElsewhere) tagNames.add("graphql");
217
+ const shadowed = callNames.size ? shadowingRanges(program, callNames) : [];
218
+ /** `graphql(...)` calling gatsby's graphql */
219
+ const isGraphqlCall = (node) => {
220
+ if (node?.type !== "CallExpression") return false;
221
+ const callee = unwrapExpression(node.callee);
222
+ if (callee?.type === "Identifier") return callNames.has(callee.name) && !shadowed.some(([start, end]) => node.start >= start && node.start < end);
223
+ return (callee?.type === "MemberExpression" || callee?.type === "StaticMemberExpression") && !callee.computed && callee.property?.name === "graphql" && callee.object?.type === "Identifier" && moduleNames.has(callee.object.name);
224
+ };
225
+ const isGraphqlTag = (node) => {
226
+ if (node?.type !== "TaggedTemplateExpression") return false;
227
+ const name = tagName(node.tag);
228
+ return !!name && (node.tag.type !== "Identifier" || tagNames.has(name));
229
+ };
230
+ /** a graphql document expression (tag or call), unwrapped from TypeScript wrappers */
231
+ const documentNode = (node) => {
232
+ const inner = unwrapExpression(node);
233
+ return isGraphqlTag(inner) || isGraphqlCall(inner) ? inner : void 0;
234
+ };
235
+ const staticTagStarts = /* @__PURE__ */ new Set();
236
+ /** documents assigned to variables, by name (all of them, in source order) */
237
+ const variableInits = /* @__PURE__ */ new Map();
238
+ /** variables passed to useStaticQuery / <StaticQuery> before their declaration */
239
+ const laterStatic = /* @__PURE__ */ new Set();
240
+ const exportedTags = /* @__PURE__ */ new Map();
241
+ walk(program, (node) => {
242
+ if (node.type === "VariableDeclarator" && node.id?.type === "Identifier") {
243
+ const doc = documentNode(node.init);
244
+ if (doc) {
245
+ const inits = variableInits.get(node.id.name) ?? [];
246
+ inits.push(doc);
247
+ variableInits.set(node.id.name, inits);
248
+ }
249
+ }
250
+ if (node.type === "ExportNamedDeclaration" && node.declaration?.type === "VariableDeclaration") for (const d of node.declaration.declarations) {
251
+ const doc = documentNode(d.init);
252
+ if (doc && d.id?.type === "Identifier") exportedTags.set(doc.start, d.id.name);
253
+ }
254
+ if (node.type === "CallExpression") {
255
+ const callee = node.callee;
256
+ const name = callee?.type === "Identifier" ? callee.name : callee?.property?.name;
257
+ if (hookNames.has(name) && node.arguments?.[0]) markStatic(node.arguments[0]);
258
+ }
259
+ if (node.type === "JSXOpeningElement" && componentNames.has(node.name?.name)) {
260
+ for (const attr of node.attributes ?? []) if (attr.type === "JSXAttribute" && attr.name?.name === "query" && attr.value?.type === "JSXExpressionContainer") markStatic(attr.value.expression);
261
+ }
262
+ });
263
+ function markStatic(arg) {
264
+ const doc = documentNode(arg);
265
+ if (doc) staticTagStarts.add(doc.start);
266
+ else if (unwrapExpression(arg)?.type === "Identifier") {
267
+ const name = unwrapExpression(arg).name;
268
+ const init = variableInits.get(name)?.at(-1);
269
+ if (init) staticTagStarts.add(init.start);
270
+ else laterStatic.add(name);
271
+ }
272
+ }
273
+ for (const name of laterStatic) {
274
+ const init = variableInits.get(name)?.[0];
275
+ if (init) staticTagStarts.add(init.start);
276
+ }
277
+ const tags = [];
278
+ const callErrors = [];
279
+ let error;
280
+ walk(program, (node) => {
281
+ let text;
282
+ if (isGraphqlTag(node)) {
283
+ const quasi = node.quasi;
284
+ if (quasi.expressions?.length) {
285
+ error = /* @__PURE__ */ new Error(`${file}: GraphQL tagged templates can't contain interpolations ("\${...}"). Use GraphQL fragments to share query parts.`);
286
+ return;
287
+ }
288
+ text = quasi.quasis.map((q) => q.value.cooked ?? q.value.raw).join("");
289
+ } else if (isGraphqlCall(node)) {
290
+ const arg = node.arguments?.[0];
291
+ if (arg?.type === "Literal" && typeof arg.value === "string") text = arg.value;
292
+ else if (arg?.type === "TemplateLiteral" && !arg.expressions?.length) text = arg.quasis.map((q) => q.value.cooked ?? q.value.raw).join("");
293
+ else {
294
+ const { line, column } = lineColumn(code, node.start);
295
+ callErrors.push(`${file}:${line}:${column}: the first argument of graphql() must be a string literal or a template literal without interpolations ("\${...}"), so that the query can be extracted at build time. Use GraphQL fragments to share query parts.`);
296
+ return;
297
+ }
298
+ } else return;
299
+ const { operationNames, fragmentNames } = quickNames(text);
300
+ const hasOperation = /^\s*(query\b|\{)/m.test(text.replace(/#[^\n]*/g, "")) || operationNames.length > 0;
301
+ let kind;
302
+ if (staticTagStarts.has(node.start)) kind = "static";
303
+ else if (hasOperation) kind = "page";
304
+ else kind = "fragment";
305
+ tags.push({
306
+ kind,
307
+ text,
308
+ ...node.type === "CallExpression" ? { call: true } : {},
309
+ hash: hashQuery(text),
310
+ start: node.start,
311
+ end: node.end,
312
+ exportName: exportedTags.get(node.start),
313
+ operationNames,
314
+ fragmentNames
315
+ });
316
+ });
317
+ return {
318
+ file,
319
+ tags,
320
+ error,
321
+ ...callErrors.length ? { callErrors } : {},
322
+ ...usesRegistry ? { usesRegistry } : {}
323
+ };
324
+ }
325
+ function lineColumn(code, offset) {
326
+ const before = code.slice(0, offset);
327
+ return {
328
+ line: before.split("\n").length,
329
+ column: offset - before.lastIndexOf("\n")
330
+ };
331
+ }
332
+ const SOURCE_EXTENSIONS = [
333
+ "js",
334
+ "jsx",
335
+ "mjs",
336
+ "cjs",
337
+ "ts",
338
+ "tsx",
339
+ "mts",
340
+ "cts"
341
+ ];
342
+ /**
343
+ * Files scanned for queries & fragments: site src/, plugin src/, page components
344
+ * and `.cache/fragments` (where source plugins write generated fragments, as in Gatsby).
345
+ */
346
+ async function findQueryFiles(siteDir, pluginDirs, extraFiles) {
347
+ const pattern = `**/*.{${SOURCE_EXTENSIONS.join(",")}}`;
348
+ const ignore = [
349
+ "**/node_modules/**",
350
+ "**/*.d.ts",
351
+ "**/__tests__/**",
352
+ "**/*.test.*",
353
+ "**/*.spec.*"
354
+ ];
355
+ const dirs = [
356
+ path.join(siteDir, "src"),
357
+ path.join(siteDir, ".cache", "fragments"),
358
+ ...pluginDirs.map((d) => path.join(d, "src"))
359
+ ];
360
+ const files = /* @__PURE__ */ new Set();
361
+ await Promise.all(dirs.map(async (dir) => {
362
+ if (!fs.existsSync(dir)) return;
363
+ for (const f of await glob(pattern, {
364
+ cwd: dir,
365
+ absolute: true,
366
+ ignore
367
+ })) files.add(slash(f));
368
+ }));
369
+ for (const f of extraFiles) files.add(slash(f.split("?")[0]));
370
+ return [...files];
371
+ }
372
+ export { SOURCE_EXTENSIONS, extractFromSource, findQueryFiles, hashQuery };
@@ -0,0 +1,124 @@
1
+ // src/node/query/gql-tada-introspection.ts
2
+ const nameCompare = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
3
+ function mapTypeRef(ref) {
4
+ switch (ref.kind) {
5
+ case "NON_NULL":
6
+ case "LIST": return {
7
+ kind: ref.kind,
8
+ ofType: mapTypeRef(ref.ofType)
9
+ };
10
+ default: return {
11
+ kind: ref.kind,
12
+ name: ref.name
13
+ };
14
+ }
15
+ }
16
+ const mapInputField = (field) => ({
17
+ name: field.name,
18
+ type: mapTypeRef(field.type),
19
+ defaultValue: field.defaultValue || void 0
20
+ });
21
+ const mapField = (field) => ({
22
+ name: field.name,
23
+ type: mapTypeRef(field.type)
24
+ });
25
+ const mapPossibleType = (type) => ({
26
+ kind: type.kind,
27
+ name: type.name
28
+ });
29
+ function minifyType(type) {
30
+ switch (type.kind) {
31
+ case "SCALAR": return {
32
+ kind: "SCALAR",
33
+ name: type.name
34
+ };
35
+ case "ENUM": return {
36
+ kind: "ENUM",
37
+ name: type.name,
38
+ enumValues: type.enumValues.map((value) => ({ name: value.name }))
39
+ };
40
+ case "INPUT_OBJECT": return {
41
+ kind: "INPUT_OBJECT",
42
+ name: type.name,
43
+ inputFields: type.inputFields.map(mapInputField),
44
+ isOneOf: type.isOneOf || false
45
+ };
46
+ case "OBJECT": return {
47
+ kind: "OBJECT",
48
+ name: type.name,
49
+ fields: type.fields ? type.fields.map(mapField).sort(nameCompare) : []
50
+ };
51
+ case "INTERFACE": return {
52
+ kind: "INTERFACE",
53
+ name: type.name,
54
+ fields: type.fields ? type.fields.map(mapField).sort(nameCompare) : [],
55
+ possibleTypes: type.possibleTypes ? type.possibleTypes.map(mapPossibleType).sort(nameCompare) : []
56
+ };
57
+ case "UNION": return {
58
+ kind: "UNION",
59
+ name: type.name,
60
+ possibleTypes: type.possibleTypes ? type.possibleTypes.map(mapPossibleType).sort(nameCompare) : []
61
+ };
62
+ }
63
+ }
64
+ const printName = (name) => name ? `'${name}'` : "never";
65
+ function printTypeRef(ref) {
66
+ if (ref.kind === "NON_NULL") return `{ kind: 'NON_NULL'; name: never; ofType: ${printTypeRef(ref.ofType)}; }`;
67
+ if (ref.kind === "LIST") return `{ kind: 'LIST'; name: never; ofType: ${printTypeRef(ref.ofType)}; }`;
68
+ return `{ kind: ${printName(ref.kind)}; name: ${printName(ref.name)}; ofType: null; }`;
69
+ }
70
+ const printNamedTypes = (types) => types.length ? types.map((type) => printName(type.name)).join(" | ") : "never";
71
+ function printFields(fields) {
72
+ let out = "";
73
+ for (const field of fields) out += `${printName(field.name)}: { name: ${printName(field.name)}; type: ${printTypeRef(field.type)} }; `;
74
+ return `{ ${out}}`;
75
+ }
76
+ function printType(type) {
77
+ switch (type.kind) {
78
+ case "ENUM": return `{ name: ${printName(type.name)}; enumValues: ${printNamedTypes(type.enumValues)}; }`;
79
+ case "INPUT_OBJECT": {
80
+ const fields = type.inputFields.map((field) => `{ name: ${printName(field.name)}; type: ${printTypeRef(field.type)}; defaultValue: ${field.defaultValue ? JSON.stringify(field.defaultValue) : "null"} }`).join(", ");
81
+ return `{ kind: 'INPUT_OBJECT'; name: ${printName(type.name)}; isOneOf: ${type.isOneOf || false}; inputFields: [${fields}]; }`;
82
+ }
83
+ case "OBJECT": return `{ kind: 'OBJECT'; name: ${printName(type.name)}; fields: ${printFields(type.fields)}; }`;
84
+ case "INTERFACE": return `{ kind: 'INTERFACE'; name: ${printName(type.name)}; fields: ${printFields(type.fields)}; possibleTypes: ${printNamedTypes(type.possibleTypes)}; }`;
85
+ case "UNION": return `{ kind: 'UNION'; name: ${printName(type.name)}; fields: {}; possibleTypes: ${printNamedTypes(type.possibleTypes)}; }`;
86
+ default: return "unknown";
87
+ }
88
+ }
89
+ const INTROSPECTION_TYPES = /* @__PURE__ */ new Set([
90
+ "__Directive",
91
+ "__DirectiveLocation",
92
+ "__EnumValue",
93
+ "__InputValue",
94
+ "__Field",
95
+ "__Type",
96
+ "__TypeKind",
97
+ "__Schema"
98
+ ]);
99
+ const KINDS = /* @__PURE__ */ new Set([
100
+ "SCALAR",
101
+ "ENUM",
102
+ "INPUT_OBJECT",
103
+ "OBJECT",
104
+ "INTERFACE",
105
+ "UNION"
106
+ ]);
107
+ /**
108
+ * gql.tada's preprocessed schema type (TypeScript source) of an introspection result, as
109
+ * `gql.tada generate output` writes it into a `.d.ts` file.
110
+ */
111
+ function preprocessIntrospection(introspection) {
112
+ const schema = introspection.__schema;
113
+ const typeLines = schema.types.filter((type) => !INTROSPECTION_TYPES.has(type.name) && KINDS.has(type.kind)).map(minifyType).sort(nameCompare).map((type) => ` ${printName(type.name)}: ${printType(type)};`);
114
+ return `{
115
+ name: never;
116
+ query: ${printName(schema.queryType.name)};
117
+ mutation: ${printName(schema.mutationType?.name)};
118
+ subscription: ${printName(schema.subscriptionType?.name)};
119
+ types: {
120
+ ${typeLines.join("\n")}
121
+ };
122
+ }`;
123
+ }
124
+ export { preprocessIntrospection };