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,318 @@
1
+ import { store } from "../redux/index.js";
2
+ import { getNode } from "../datastore/index.js";
3
+ import { applyTrailingSlashOption, slash } from "../utils/paths.js";
4
+ import { camelCase } from "../schema/naming.js";
5
+ import { GraphQLString } from "../gql.js";
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import slugify from "@sindresorhus/slugify";
9
+ import { glob } from "tinyglobby";
10
+ import picomatch from "picomatch";
11
+ // src/node/internal-plugins/page-creator.ts
12
+ /** `blog/index.tsx` → `/blog/`, `about.tsx` → `/about/` */
13
+ function createPath(filePath, withTrailingSlash = true, usePathBase = false) {
14
+ const { dir, name, base } = path.posix.parse(slash(filePath));
15
+ const parsedBase = base === "index" ? "" : base;
16
+ const parsedName = name === "index" ? "" : name;
17
+ const postfix = withTrailingSlash ? "/" : "";
18
+ return path.posix.join("/", dir, usePathBase ? parsedBase : parsedName, postfix);
19
+ }
20
+ const isTestFile = picomatch(["**/__tests__/**/*.?(m)[jt]s?(x)", "**/?(*.)+(spec|test).?(m)[jt]s?(x)"]);
21
+ function validatePath(filePath) {
22
+ const { name } = path.posix.parse(slash(filePath));
23
+ if (name.startsWith("_") || name.startsWith(".") || name.startsWith("template-")) return false;
24
+ if (filePath.endsWith(".d.ts")) return false;
25
+ return !isTestFile(slash(filePath));
26
+ }
27
+ function ignorePath(filePath, ignore) {
28
+ if (!ignore) return false;
29
+ const settings = Array.isArray(ignore) ? { patterns: ignore } : typeof ignore === "string" ? { patterns: [ignore] } : ignore;
30
+ if (!settings.patterns?.length) return false;
31
+ return picomatch(settings.patterns, settings.options ?? {})(slash(filePath));
32
+ }
33
+ /** `/users/[id]/` → `/users/:id`, `/app/[...]/` → `/app/*`, `/app/[...rest]` → `/app/*rest` */
34
+ function getMatchPath(srcPagesPath) {
35
+ if (!srcPagesPath.includes("[")) return void 0;
36
+ return srcPagesPath.replace(/\[\.\.\.\]/g, "*").replace(/\[\.\.\.([^\]]+)\]/g, "*$1").replace(/\[([^\]]+)\]/g, ":$1").replace(/\/$/, "");
37
+ }
38
+ function removeFileExtension(p) {
39
+ return p.replace(/\.[a-z]+$/, "");
40
+ }
41
+ function extractModel(p) {
42
+ return /\{([a-zA-Z_][\w]*)\./.exec(p)?.[1] ?? "";
43
+ }
44
+ function extractField(filePart) {
45
+ const content = filePart.match(/\{.*?\}/g);
46
+ if (!content) return [""];
47
+ return content.map((c) => c.replace(/[{}]/g, "").replace(/[a-zA-Z_][\w]*\./, ""));
48
+ }
49
+ function extractFieldWithoutUnion(filePart) {
50
+ return extractField(filePart).map((e) => e.replace(/\(.*\)__/g, ""));
51
+ }
52
+ const switchToPeriodDelimiters = (s) => s.replace(/__/g, ".");
53
+ function deriveNesting(part) {
54
+ if (!part.includes("__")) return part;
55
+ return part.split("__").reverse().reduce((acc, p) => {
56
+ const converted = acc.replace(/\(/g, "... on ").replace(/\)/g, "");
57
+ return converted ? `${p}{${converted}}` : `${p}${converted}`;
58
+ }, "");
59
+ }
60
+ function getValue(obj, key) {
61
+ return key.split(".").reduce((o, k) => o == null ? void 0 : o[k], obj);
62
+ }
63
+ const slugCaches = /* @__PURE__ */ new WeakMap();
64
+ const NO_OPTIONS = {};
65
+ const SLUG_CACHE_SIZE = 1e4;
66
+ function cachedSlugify(value, options) {
67
+ const key = options ?? NO_OPTIONS;
68
+ if (typeof key !== "object") return slugify(value, options);
69
+ let cache = slugCaches.get(key);
70
+ if (!cache) slugCaches.set(key, cache = /* @__PURE__ */ new Map());
71
+ let slug = cache.get(value);
72
+ if (slug === void 0) {
73
+ slug = slugify(value, options);
74
+ if (cache.size >= SLUG_CACHE_SIZE) cache.clear();
75
+ cache.set(value, slug);
76
+ }
77
+ return slug;
78
+ }
79
+ function safeSlugify(value, options) {
80
+ return String(value).split("/").map((v) => cachedSlugify(v, options)).join("/");
81
+ }
82
+ /** the field paths (period-delimited) that the `{…}` parts of a collection route read */
83
+ function collectionFieldKeys(filePath) {
84
+ return (filePath.match(/\{.*?\}/g) ?? []).map((slugPart) => switchToPeriodDelimiters(extractFieldWithoutUnion(slugPart)[0]));
85
+ }
86
+ /**
87
+ * `resolved`: field values resolved through the schema (gatsbyPath, as Gatsby's getFieldValue),
88
+ * which take precedence over the raw node's values.
89
+ */
90
+ function derivePath(filePath, node, slugifyOptions, resolved) {
91
+ let errors = 0;
92
+ let modifiedPath = removeFileExtension(filePath);
93
+ const slugParts = filePath.match(/\{.*?\}/g) ?? [];
94
+ for (const slugPart of slugParts) {
95
+ const key = switchToPeriodDelimiters(extractFieldWithoutUnion(slugPart)[0]);
96
+ const value = getValue(node?.nodes?.[0], key) ?? resolved?.[key] ?? getValue(node, key);
97
+ if (value === void 0) {
98
+ errors++;
99
+ continue;
100
+ }
101
+ modifiedPath = modifiedPath.replace(slugPart, safeSlugify(value, slugifyOptions));
102
+ }
103
+ modifiedPath = modifiedPath.replace(/\/\/+/g, "/");
104
+ if (/^\/?$/.test(modifiedPath)) modifiedPath = "index";
105
+ return {
106
+ errors,
107
+ derivedPath: modifiedPath
108
+ };
109
+ }
110
+ /**
111
+ * Checks the `{Model.field__subfield}` parts of a collection route's file path (as Gatsby's
112
+ * isValidCollectionPathImplementation). Returns the error message, or undefined when it is valid.
113
+ */
114
+ function validateCollectionPath(filePath) {
115
+ for (const part of slash(filePath).split("/")) {
116
+ if (!part.includes("{") && !part.includes("}")) continue;
117
+ const message = `Collection page builder encountered an error parsing the filepath. To use collection paths the schema to follow is {Model.field__subfield}. The problematic part is: ${part}.`;
118
+ const models = Array.from(part.matchAll(/\{([a-zA-Z_]\w*)./g), (m) => m[1]);
119
+ const fields = Array.from(part.matchAll(/.*?((?<=\w\.)[^}]*)}/g), (m) => m[1]);
120
+ if (!models.length || !fields.length || models.length !== fields.length) return message;
121
+ if (!models.every((m) => /^[a-zA-Z_]\w*$/.test(m))) return message;
122
+ if (!fields.every((f) => /^[a-zA-Z_][\w()]*$/.test(f))) return message;
123
+ }
124
+ }
125
+ /**
126
+ * Checks the `filePath` argument of `gatsbyPath` (as Gatsby's validatePathQuery). Returns the error
127
+ * message, or undefined when it is valid.
128
+ */
129
+ function validatePathQuery(filePath) {
130
+ if (!filePath.startsWith("/")) return `PageCreator: To query node "gatsbyPath" the "filePath" argument must be an absolute path, starting with a /\nPlease change this to: "/${filePath}"`;
131
+ if (/\.[a-z]+$/i.test(filePath)) return `PageCreator: To query node "gatsbyPath" the "filePath" argument must omit the file extension\nPlease change ${filePath} to "${filePath.replace(/\.[a-z]+$/i, "")}"`;
132
+ if (filePath.includes("src/pages")) return `PageCreator: To query node "gatsbyPath" the "filePath" argument must omit the src/pages prefix.\nPlease change this to: "${filePath.replace(/\/?src\/pages\//, "")}"`;
133
+ if (filePath.endsWith("index")) return `PageCreator: To query node "gatsbyPath" the "filePath" argument must omit index.\nPlease change this to: "${filePath.replace(/index$/, "")}"`;
134
+ }
135
+ function getCollectionRouteParams(urlTemplate, urlPath) {
136
+ const params = {};
137
+ const cleaned = removeFileExtension(urlTemplate);
138
+ const templateParts = cleaned.split("/");
139
+ const templateRegex = cleaned.replace(/\./g, "\\.").replace(/(\{.*?\})/g, "(.+)").split("/");
140
+ const urlParts = urlPath.split("/");
141
+ templateParts.forEach((part, i) => {
142
+ if (!part.includes("{") || !part.includes("}")) return;
143
+ const match = urlParts[i]?.match(templateRegex[i]);
144
+ if (!match) return;
145
+ extractFieldWithoutUnion(part).forEach((k, j) => {
146
+ params[k] = match[j + 1];
147
+ });
148
+ });
149
+ return params;
150
+ }
151
+ function generateCollectionQuery(model, filePath) {
152
+ const parts = slash(filePath).split("/");
153
+ if (!parts.some((s) => s.includes(".id}"))) parts.push("{Model.id}");
154
+ parts.push("{Model.internal__contentFilePath}");
155
+ const fields = parts.filter((p) => p.includes("{") && p.includes("}")).flatMap((p) => extractField(p).map(deriveNesting));
156
+ return `{${camelCase(`all ${model}`)}{nodes{${[...new Set(fields)].join(",")}}}}`;
157
+ }
158
+ function reverseLookupParams(node, filePath) {
159
+ const params = { id: node.id };
160
+ for (const part of slash(filePath).split("/")) for (const extract of extractFieldWithoutUnion(part)) {
161
+ if (!extract) continue;
162
+ params[extract] = getValue(node, switchToPeriodDelimiters(extract));
163
+ }
164
+ return params;
165
+ }
166
+ function pageExtensions() {
167
+ return store.getState().program.extensions.filter((e) => [
168
+ ".js",
169
+ ".jsx",
170
+ ".ts",
171
+ ".tsx",
172
+ ".mjs",
173
+ ".cjs",
174
+ ".mdx",
175
+ ".md"
176
+ ].includes(e) || !e.endsWith(".json"));
177
+ }
178
+ /** extensions of page files, with their dot: the site's resolvable extensions (e.g. `.mdx`) included */
179
+ function pageFileExtensions() {
180
+ return pageExtensions().filter((e) => e !== ".json" && e !== ".wasm");
181
+ }
182
+ async function findPageFiles(pagesPath) {
183
+ if (!fs.existsSync(pagesPath)) return [];
184
+ const exts = pageFileExtensions().map((e) => e.slice(1));
185
+ return (await glob(`**/*.{${exts.join(",")}}`, {
186
+ cwd: pagesPath,
187
+ ignore: ["**/node_modules/**"]
188
+ })).sort();
189
+ }
190
+ function createPageCreatorPlugin(options) {
191
+ const pagesPath = path.resolve(String(options.path ?? "src/pages"));
192
+ const collectionTypes = /* @__PURE__ */ new Map();
193
+ const state = {
194
+ files: /* @__PURE__ */ new Set(),
195
+ pathChecked: false
196
+ };
197
+ const createFilePage = (filePath, actions) => {
198
+ if (!validatePath(filePath) || ignorePath(filePath, options.ignore)) return;
199
+ if (filePath.includes("{")) return;
200
+ const absolutePath = slash(path.join(pagesPath, filePath));
201
+ const trailingSlash = store.getState().config.trailingSlash;
202
+ const createdPath = createPath(filePath);
203
+ actions.createPage({
204
+ path: applyTrailingSlashOption(createdPath, trailingSlash),
205
+ matchPath: filePath.includes("[") ? getMatchPath(createdPath) : void 0,
206
+ component: absolutePath,
207
+ context: {}
208
+ });
209
+ };
210
+ return {
211
+ name: "gatsby-plugin-page-creator",
212
+ resolve: pagesPath,
213
+ options: {
214
+ ...options,
215
+ path: pagesPath
216
+ },
217
+ module: {
218
+ async onPluginInit() {
219
+ collectionTypes.clear();
220
+ for (const file of await findPageFiles(pagesPath)) {
221
+ if (!file.includes("{") || !validatePath(file)) continue;
222
+ const model = extractModel(file);
223
+ if (!model) continue;
224
+ const key = camelCase(`all ${model}`);
225
+ collectionTypes.set(key, [...collectionTypes.get(key) ?? [], file]);
226
+ }
227
+ },
228
+ async createPagesStatefully({ actions, reporter }) {
229
+ if (!state.pathChecked && options.pathCheck !== false && !fs.existsSync(pagesPath)) reporter.panic({ context: { sourceMessage: `The path passed to gatsby-plugin-page-creator does not exist on your file system:\n${pagesPath}\nPlease pick a path to an existing directory.` } });
230
+ state.pathChecked = true;
231
+ const files = await findPageFiles(pagesPath);
232
+ state.files = new Set(files);
233
+ for (const file of files) createFilePage(file, actions);
234
+ },
235
+ async createPages({ actions, graphql, reporter }) {
236
+ const trailingSlash = store.getState().config.trailingSlash;
237
+ const files = await findPageFiles(pagesPath);
238
+ for (const filePath of files) {
239
+ if (!filePath.includes("{") || !validatePath(filePath) || ignorePath(filePath, options.ignore)) continue;
240
+ const absolutePath = slash(path.join(pagesPath, filePath));
241
+ const pathError = validateCollectionPath(filePath);
242
+ if (pathError) {
243
+ reporter.panicOnBuild({ context: { sourceMessage: `${pathError}\n${absolutePath}` } });
244
+ continue;
245
+ }
246
+ if (/\b(unstable_)?collectionGraphql\b/.test(fs.readFileSync(absolutePath, "utf8"))) reporter.panicOnBuild({ context: { sourceMessage: `The "collectionGraphql" (or "unstable_collectionGraphql") API was removed. Please use the "createPages" API instead to filter collection routes.\n${absolutePath}` } });
247
+ const model = extractModel(filePath);
248
+ if (!model) continue;
249
+ const { data, errors } = await graphql(generateCollectionQuery(model, filePath));
250
+ if (errors?.length) {
251
+ reporter.panicOnBuild({ context: { sourceMessage: `Could not create collection route pages for "${filePath}":\n${errors.map((e) => e.message).join("\n")}` } });
252
+ continue;
253
+ }
254
+ const nodes = Object.values(Object.values(data ?? {})[0] ?? {})[0] ?? [];
255
+ const known = /* @__PURE__ */ new Set();
256
+ const missing = [];
257
+ for (const node of nodes) {
258
+ const { derivedPath, errors } = derivePath(filePath, node, options.slugify);
259
+ if (errors) {
260
+ missing.push(String(node.id));
261
+ continue;
262
+ }
263
+ const createdPath = createPath(derivedPath, derivedPath.endsWith("/"), true);
264
+ const pagePath = applyTrailingSlashOption(createdPath, trailingSlash);
265
+ if (known.has(pagePath)) continue;
266
+ known.add(pagePath);
267
+ const params = getCollectionRouteParams(createPath(filePath), createdPath);
268
+ const contentFilePath = node.internal?.contentFilePath;
269
+ actions.createPage({
270
+ path: pagePath,
271
+ matchPath: getMatchPath(createdPath),
272
+ component: contentFilePath ? `${absolutePath}?__contentFilePath=${contentFilePath}` : absolutePath,
273
+ context: {
274
+ ...reverseLookupParams(node, filePath),
275
+ __params: params
276
+ }
277
+ });
278
+ }
279
+ if (missing.length) {
280
+ const ids = missing.slice(0, 5).join(", ") + (missing.length > 5 ? ", …" : "");
281
+ reporter.panicOnBuild({ context: { sourceMessage: `Could not find a value in the node for ${filePath}. Please make sure that the syntax is correct and supported.\nNo page was created for ${missing.length} node${missing.length > 1 ? "s" : ""} (id: ${ids}).` } });
282
+ }
283
+ }
284
+ },
285
+ setFieldsOnGraphQLNodeType({ type }) {
286
+ const key = camelCase(`all ${type.name}`);
287
+ if (!collectionTypes.has(key)) return {};
288
+ const trailingSlash = store.getState().config.trailingSlash;
289
+ return { gatsbyPath: {
290
+ type: GraphQLString,
291
+ args: { filePath: { type: GraphQLString } },
292
+ async resolve(source, { filePath }, context) {
293
+ const queryError = validatePathQuery(String(filePath));
294
+ if (queryError) throw new Error(queryError);
295
+ const appendParents = (n) => {
296
+ const copy = { ...n };
297
+ if (copy.parent) {
298
+ const parent = getNode(copy.parent);
299
+ if (parent) copy.parent = appendParents(parent);
300
+ }
301
+ return copy;
302
+ };
303
+ let resolved;
304
+ if (context?.nodeModel) {
305
+ resolved = {};
306
+ for (const key of collectionFieldKeys(filePath)) try {
307
+ resolved[key] = await context.nodeModel.getFieldValue(source, key);
308
+ } catch {}
309
+ }
310
+ const { derivedPath } = derivePath(filePath, appendParents(source), options.slugify, resolved);
311
+ return applyTrailingSlashOption(createPath(derivedPath, derivedPath.endsWith("/"), true), trailingSlash);
312
+ }
313
+ } };
314
+ }
315
+ }
316
+ };
317
+ }
318
+ export { createPageCreatorPlugin, createPath, derivePath, findPageFiles, getMatchPath, ignorePath, pageFileExtensions, validateCollectionPath, validatePath, validatePathQuery };
@@ -0,0 +1,160 @@
1
+ import { isBun } from "../utils/runtime.js";
2
+ import { createRequire } from "node:module";
3
+ import { threadId } from "node:worker_threads";
4
+ import { createHash } from "node:crypto";
5
+ import path from "node:path";
6
+ import fs from "node:fs";
7
+ import { pathToFileURL } from "node:url";
8
+ // src/node/loader/import-module.ts
9
+ const TS_EXT = /\.(ts|mts|cts|tsx|jsx)$/;
10
+ const ID_RE = /^[\w@][\w./@-]*$/;
11
+ /**
12
+ * Candidate extensions for Gatsby API files. TypeScript first: goatly treats TS as first-class.
13
+ */
14
+ const API_FILE_EXTENSIONS = [
15
+ ".ts",
16
+ ".mts",
17
+ ".tsx",
18
+ ".cts",
19
+ ".js",
20
+ ".mjs",
21
+ ".cjs",
22
+ ".jsx"
23
+ ];
24
+ /** Finds `<dir>/<base>.{ts,mts,js,...}` */
25
+ function resolveApiFile(dir, base) {
26
+ for (const ext of API_FILE_EXTENSIONS) {
27
+ const file = path.join(dir, base + ext);
28
+ if (fs.existsSync(file)) return file;
29
+ }
30
+ }
31
+ /**
32
+ * The temp modules `importModule` writes next to a file: removed once imported, but left behind by
33
+ * a thread terminated meanwhile (e.g. a query worker still starting when the queries are done)
34
+ */
35
+ const TEMP_MODULE = /\.goatly-[0-9a-f]{8}-\d+-\d+\.mjs$/;
36
+ function isInNodeModules(file) {
37
+ return file.split(path.sep).includes("node_modules");
38
+ }
39
+ /**
40
+ * Loads a Node module written in TypeScript, ESM or CommonJS.
41
+ *
42
+ * On Bun every file is imported natively (Bun runs TS/ESM/CJS out of the box).
43
+ * On Node.js plain JavaScript files inside `node_modules` are loaded natively. Everything else
44
+ * (site files and local plugins, any TypeScript) is bundled with Rolldown first –
45
+ * this gives full TS support (incl. enums, path-less imports, JSX) without a
46
+ * `ts-node`/babel setup and works for CJS and ESM alike. Bare imports stay external
47
+ * so they are resolved by Node exactly as in the source location.
48
+ */
49
+ async function importModule(file, options = {}) {
50
+ if (isBun && !options.bundle) return await import(file);
51
+ if (!(options.bundle || TS_EXT.test(file) || !isInNodeModules(file))) return await import(pathToFileURL(file).href);
52
+ const code = await bundleFile(file, options);
53
+ const tmpFile = `${file}.goatly-${createHash("sha1").update(code).digest("hex").slice(0, 8)}-${process.pid}-${threadId}.mjs`;
54
+ await fs.promises.writeFile(tmpFile, code);
55
+ try {
56
+ return await import(pathToFileURL(tmpFile).href);
57
+ } finally {
58
+ await fs.promises.rm(tmpFile, { force: true });
59
+ }
60
+ }
61
+ let viteRolldown;
62
+ /**
63
+ * The rolldown that Vite runs, resolved from Vite's own location. goatly does not depend on
64
+ * rolldown itself: Vite pins rolldown with a tilde range, so a dependency of our own would install a
65
+ * second rolldown (with a second ~21 MB native binding) whenever the two ranges drift apart.
66
+ */
67
+ function loadViteRolldown() {
68
+ if (!viteRolldown) {
69
+ const vitePackage = createRequire(import.meta.url).resolve("vite/package.json");
70
+ viteRolldown = import(pathToFileURL(createRequire(vitePackage).resolve("rolldown")).href);
71
+ }
72
+ return viteRolldown;
73
+ }
74
+ async function bundleFile(file, options = {}) {
75
+ const { rolldown } = await loadViteRolldown();
76
+ const dirnameVar = "__goatly_injected_dirname";
77
+ const filenameVar = "__goatly_injected_filename";
78
+ const importMetaUrlVar = "__goatly_injected_import_meta_url";
79
+ const bundle = await rolldown({
80
+ input: file,
81
+ platform: "node",
82
+ logLevel: "silent",
83
+ resolve: {
84
+ alias: options.alias,
85
+ extensions: [
86
+ ".ts",
87
+ ".tsx",
88
+ ".mts",
89
+ ".cts",
90
+ ".mjs",
91
+ ".js",
92
+ ".jsx",
93
+ ".cjs",
94
+ ".json"
95
+ ],
96
+ mainFields: ["module", "main"]
97
+ },
98
+ transform: {
99
+ define: {
100
+ __dirname: dirnameVar,
101
+ __filename: filenameVar,
102
+ "import.meta.url": importMetaUrlVar,
103
+ "import.meta.dirname": dirnameVar,
104
+ "import.meta.filename": filenameVar
105
+ },
106
+ jsx: { runtime: "automatic" }
107
+ },
108
+ external(id, importer) {
109
+ if (id.startsWith("node:")) return true;
110
+ if (id.startsWith(".") || path.isAbsolute(id)) return false;
111
+ if (options.alias && Object.keys(options.alias).some((a) => id === a || id.startsWith(`${a}/`))) return false;
112
+ return ID_RE.test(id) || !importer;
113
+ },
114
+ plugins: [{
115
+ name: "goatly:inject-file-scope-variables",
116
+ transform: {
117
+ filter: { id: /\.(m|c)?[jt]sx?$/ },
118
+ handler(code, id) {
119
+ if (!/__dirname|__filename|import\.meta/.test(code)) return null;
120
+ return {
121
+ code: `const ${dirnameVar} = ${JSON.stringify(path.dirname(id))};const ${filenameVar} = ${JSON.stringify(id)};const ${importMetaUrlVar} = ${JSON.stringify(pathToFileURL(id).href)};` + code,
122
+ map: null
123
+ };
124
+ }
125
+ }
126
+ }]
127
+ });
128
+ try {
129
+ const { output } = await bundle.generate({
130
+ format: "esm",
131
+ sourcemap: "inline",
132
+ codeSplitting: false
133
+ });
134
+ return output[0].code;
135
+ } finally {
136
+ await bundle.close();
137
+ }
138
+ }
139
+ /** Returns the module's API object, unwrapping CJS `default` exports. */
140
+ function normalizeModuleExports(mod) {
141
+ if (!mod) return {};
142
+ if (mod.default && typeof mod.default === "object" && !Array.isArray(mod.default)) {
143
+ const keys = Object.keys(mod).filter((k) => k !== "default" && k !== "module.exports");
144
+ if (keys.length === 0 || mod.__esModule || mod.default.__esModule) return {
145
+ ...mod.default,
146
+ ...pick(mod, keys)
147
+ };
148
+ return {
149
+ ...mod.default,
150
+ ...pick(mod, keys)
151
+ };
152
+ }
153
+ return mod;
154
+ }
155
+ function pick(obj, keys) {
156
+ const out = {};
157
+ for (const k of keys) out[k] = obj[k];
158
+ return out;
159
+ }
160
+ export { API_FILE_EXTENSIONS, TEMP_MODULE, bundleFile, importModule, loadViteRolldown, normalizeModuleExports, resolveApiFile };
@@ -0,0 +1,66 @@
1
+ import { getNode } from "./datastore/index.js";
2
+ import { store } from "./redux/index.js";
3
+ import { recordPathDependency } from "./query/dependencies.js";
4
+ import { importModule, normalizeModuleExports } from "./loader/import-module.js";
5
+ import { resolvePluginModulePath } from "./plugins/resolve-plugin.js";
6
+ // src/node/node-helpers.ts
7
+ const mainModules = /* @__PURE__ */ new Map();
8
+ function loadMainModule(pluginName, resolve, version) {
9
+ let p = mainModules.get(pluginName);
10
+ if (!p) {
11
+ p = (async () => {
12
+ const file = resolvePluginModulePath({
13
+ name: pluginName,
14
+ resolve,
15
+ version,
16
+ id: "",
17
+ packageJson: {}
18
+ });
19
+ if (!file) return {};
20
+ try {
21
+ return normalizeModuleExports(await importModule(file));
22
+ } catch {
23
+ return {};
24
+ }
25
+ })();
26
+ mainModules.set(pluginName, p);
27
+ }
28
+ return p;
29
+ }
30
+ /**
31
+ * Concurrent `loadNodeContent` calls: transformers call it for every node they get in
32
+ * `onCreateNode`, i.e. for every file at once on large sites – without a limit that exceeds the
33
+ * open files limit (EMFILE).
34
+ */
35
+ const MAX_CONCURRENT_LOADS = 256;
36
+ let activeLoads = 0;
37
+ const waitingLoads = [];
38
+ async function limitLoad(fn) {
39
+ if (activeLoads >= MAX_CONCURRENT_LOADS) await new Promise((resolve) => waitingLoads.push(resolve));
40
+ activeLoads++;
41
+ try {
42
+ return await fn();
43
+ } finally {
44
+ activeLoads--;
45
+ waitingLoads.shift()?.();
46
+ }
47
+ }
48
+ /**
49
+ * Same as Gatsby's `loadNodeContent`: asks the owner plugin's `loadNodeContent`
50
+ * (exported from gatsby-node or – like gatsby-source-filesystem – from the main entry).
51
+ */
52
+ async function loadNodeContent(node) {
53
+ if (typeof node.internal.content === "string") return node.internal.content;
54
+ const owner = store.getState().flattenedPlugins.find((p) => p.name === node.internal.owner);
55
+ let fn = owner?.module?.loadNodeContent;
56
+ if (!fn && owner) fn = (await loadMainModule(owner.name, owner.resolve, owner.version)).loadNodeContent;
57
+ if (typeof fn !== "function") throw new Error(`Could not find function loadNodeContent for plugin ${node.internal.owner}`);
58
+ const load = fn;
59
+ return limitLoad(async () => load(node));
60
+ }
61
+ /** Gatsby API helper: reads a node and records it as a dependency of the query for `path`. */
62
+ function getNodeAndSavePathDependency(id, path) {
63
+ recordPathDependency(path, { nodeId: id });
64
+ return getNode(id);
65
+ }
66
+ export { getNodeAndSavePathDependency, loadNodeContent };