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,193 @@
1
+ import { getDataStore } from "../datastore/index.js";
2
+ import { recordNodeChange, recordNodeDelete } from "./node-changes.js";
3
+ import { initialState } from "./state.js";
4
+ // src/node/redux/reducers.ts
5
+ /** fromPath → JSON of the redirects stored for it, per state (identical redirects are stored once) */
6
+ const redirectIndexes = /* @__PURE__ */ new WeakMap();
7
+ /** the node's stored type, read before the datastore changes */
8
+ const storedTypeOf = (id) => id === void 0 ? void 0 : getDataStore().getNodeType?.(id);
9
+ const setNodeField = (_s, action) => {
10
+ const node = action.payload;
11
+ const previousType = storedTypeOf(node?.id);
12
+ getDataStore().setNode(node);
13
+ recordNodeChange(node, previousType, "deferDigest" in action && action.deferDigest === true);
14
+ };
15
+ const setBabel = (s, action) => {
16
+ const stage = action.payload?.stage ?? "develop";
17
+ const entry = s.babelrc.stages[stage] ??= {
18
+ plugins: [],
19
+ presets: [],
20
+ options: {}
21
+ };
22
+ if (action.type === "SET_BABEL_OPTIONS") Object.assign(entry.options, action.payload.options);
23
+ else if (action.type === "SET_BABEL_PLUGIN") entry.plugins.push(action.payload);
24
+ else entry.presets.push(action.payload);
25
+ };
26
+ const reducers = {
27
+ SET_PROGRAM(s, action) {
28
+ s.program = {
29
+ ...s.program,
30
+ ...action.payload
31
+ };
32
+ },
33
+ SET_SITE_CONFIG(s, action) {
34
+ s.config = action.payload;
35
+ },
36
+ SET_SITE_FLATTENED_PLUGINS(s, action) {
37
+ s.flattenedPlugins = action.payload;
38
+ },
39
+ CREATE_NODE(s, action) {
40
+ const node = action.payload;
41
+ const oldNode = action.oldNode;
42
+ const previousType = oldNode?.internal?.type ?? storedTypeOf(node?.id);
43
+ getDataStore().setNode(node, oldNode);
44
+ recordNodeChange(node, previousType);
45
+ s.nodesTouched.add(node.id);
46
+ if (node.internal.counter && node.internal.counter > s.status.LAST_NODE_COUNTER) s.status.LAST_NODE_COUNTER = node.internal.counter;
47
+ },
48
+ ADD_FIELD_TO_NODE: setNodeField,
49
+ ADD_CHILD_NODE_TO_PARENT_NODE: setNodeField,
50
+ DELETE_NODE(s, action) {
51
+ const node = action.payload;
52
+ if (!node) return;
53
+ const storedType = storedTypeOf(node.id);
54
+ getDataStore().deleteNode(node);
55
+ recordNodeDelete(node, storedType);
56
+ s.nodesTouched.delete(node.id);
57
+ },
58
+ TOUCH_NODE(s, action) {
59
+ s.nodesTouched.add(action.payload);
60
+ },
61
+ CREATE_PAGE(s, action) {
62
+ const page = action.payload;
63
+ s.pages.set(page.path, page);
64
+ let component = s.components.get(page.componentPath);
65
+ if (!component) {
66
+ component = {
67
+ componentPath: page.componentPath,
68
+ componentChunkName: page.componentChunkName,
69
+ query: "",
70
+ pages: /* @__PURE__ */ new Set(),
71
+ isInBootstrap: true
72
+ };
73
+ s.components.set(page.componentPath, component);
74
+ }
75
+ component.pages.add(page.path);
76
+ },
77
+ DELETE_PAGE(s, action) {
78
+ const page = s.pages.get(action.payload.path);
79
+ if (!page) return;
80
+ s.pages.delete(page.path);
81
+ const component = s.components.get(page.componentPath);
82
+ if (component) {
83
+ component.pages.delete(page.path);
84
+ if (component.pages.size === 0) s.components.delete(page.componentPath);
85
+ }
86
+ },
87
+ CREATE_REDIRECT(s, action) {
88
+ let index = redirectIndexes.get(s);
89
+ if (!index) redirectIndexes.set(s, index = /* @__PURE__ */ new Map());
90
+ let seen = index.get(action.payload.fromPath);
91
+ if (!seen) index.set(action.payload.fromPath, seen = /* @__PURE__ */ new Set());
92
+ const json = JSON.stringify(action.payload);
93
+ if (seen.has(json)) return;
94
+ seen.add(json);
95
+ s.redirects.push(action.payload);
96
+ },
97
+ SET_PLUGIN_STATUS(s, action) {
98
+ const name = action.plugin?.name ?? "unknown";
99
+ s.status.plugins[name] = {
100
+ ...s.status.plugins[name],
101
+ ...action.payload
102
+ };
103
+ },
104
+ CREATE_TYPES(s, action) {
105
+ const types = Array.isArray(action.payload) ? action.payload : [action.payload];
106
+ for (const typeOrTypeDef of types) s.schemaCustomization.types.push({
107
+ typeOrTypeDef,
108
+ plugin: action.plugin ?? void 0
109
+ });
110
+ },
111
+ CREATE_FIELD_EXTENSION(s, action) {
112
+ const { name, extension } = action.payload;
113
+ s.schemaCustomization.fieldExtensions[name] = extension;
114
+ },
115
+ ADD_THIRD_PARTY_SCHEMA(s, action) {
116
+ s.schemaCustomization.thirdPartySchemas.push(action.payload);
117
+ },
118
+ PRINT_SCHEMA_REQUESTED(s, action) {
119
+ s.schemaCustomization.printConfig = action.payload;
120
+ },
121
+ CREATE_RESOLVER_CONTEXT(s, action) {
122
+ s.schemaCustomization.context = {
123
+ ...s.schemaCustomization.context,
124
+ ...action.payload
125
+ };
126
+ },
127
+ CLEAR_SCHEMA_CUSTOMIZATION(s) {
128
+ s.schemaCustomization = {
129
+ ...initialState().schemaCustomization,
130
+ composer: s.schemaCustomization.composer
131
+ };
132
+ },
133
+ SET_SCHEMA(s, action) {
134
+ s.schema = action.payload;
135
+ },
136
+ SET_SCHEMA_COMPOSER(s, action) {
137
+ s.schemaCustomization.composer = action.payload;
138
+ },
139
+ QUERY_EXTRACTED(s, action) {
140
+ const component = s.components.get(action.payload.componentPath);
141
+ if (component) component.query = action.payload.query;
142
+ },
143
+ REPLACE_STATIC_QUERY(s, action) {
144
+ s.staticQueryComponents.set(action.payload.id, action.payload);
145
+ },
146
+ REMOVE_STATIC_QUERY(s, action) {
147
+ s.staticQueryComponents.delete(action.payload);
148
+ },
149
+ SET_WEBPACK_CONFIG(s, action) {
150
+ s.webpack = deepMerge(s.webpack, action.payload);
151
+ },
152
+ REPLACE_WEBPACK_CONFIG(s, action) {
153
+ s.webpack = action.payload;
154
+ },
155
+ SET_BABEL_OPTIONS: setBabel,
156
+ SET_BABEL_PLUGIN: setBabel,
157
+ SET_BABEL_PRESET: setBabel,
158
+ CREATE_JOB_V2(s, action) {
159
+ s.jobsV2.incomplete.set(action.payload.job.contentDigest, { job: action.payload.job });
160
+ },
161
+ END_JOB_V2(s, action) {
162
+ s.jobsV2.incomplete.delete(action.payload.jobContentDigest);
163
+ s.jobsV2.complete.set(action.payload.jobContentDigest, { result: action.payload.result });
164
+ },
165
+ SET_REQUEST_HEADERS(s, action) {
166
+ s.requestHeaders.set(action.payload.domain, action.payload.headers);
167
+ },
168
+ ENABLE_STATEFUL_SOURCE_PLUGIN(s, action) {
169
+ if (action.plugin?.name) s.statefulSourcePlugins.add(action.plugin.name);
170
+ }
171
+ };
172
+ /**
173
+ * Applies an action to the state (in place). Actions without a reducer (e.g. BOOTSTRAP_FINISHED,
174
+ * or plugins' own) only reach listeners.
175
+ */
176
+ function reduce(s, action) {
177
+ if (!Object.hasOwn(reducers, action.type)) return;
178
+ const reducer = reducers[action.type];
179
+ reducer(s, action);
180
+ }
181
+ function deepMerge(target, source) {
182
+ if (Array.isArray(target) && Array.isArray(source)) return [...target, ...source];
183
+ if (isPlainObject(target) && isPlainObject(source)) {
184
+ const out = { ...target };
185
+ for (const key of Object.keys(source)) out[key] = key in target ? deepMerge(target[key], source[key]) : source[key];
186
+ return out;
187
+ }
188
+ return source;
189
+ }
190
+ function isPlainObject(v) {
191
+ return v !== null && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
192
+ }
193
+ export { deepMerge, isPlainObject, reduce };
@@ -0,0 +1,71 @@
1
+ // src/node/redux/state.ts
2
+ function initialState() {
3
+ return {
4
+ program: {
5
+ directory: process.cwd(),
6
+ command: "build",
7
+ sitePackageJson: {},
8
+ prefixPaths: false,
9
+ host: "localhost",
10
+ port: 8e3,
11
+ extensions: [
12
+ ".mjs",
13
+ ".js",
14
+ ".jsx",
15
+ ".wasm",
16
+ ".json",
17
+ ".tsx",
18
+ ".ts"
19
+ ],
20
+ browserslist: [],
21
+ publicDir: "",
22
+ cacheDir: ""
23
+ },
24
+ config: {
25
+ siteMetadata: {},
26
+ plugins: [],
27
+ pathPrefix: "",
28
+ assetPrefix: "",
29
+ trailingSlash: "always",
30
+ polyfill: false,
31
+ jsxRuntime: "automatic",
32
+ graphqlTypegen: false,
33
+ flags: {},
34
+ mapping: {},
35
+ headers: []
36
+ },
37
+ flattenedPlugins: [],
38
+ pages: /* @__PURE__ */ new Map(),
39
+ components: /* @__PURE__ */ new Map(),
40
+ staticQueryComponents: /* @__PURE__ */ new Map(),
41
+ redirects: [],
42
+ status: {
43
+ plugins: {},
44
+ PLUGINS_HASH: "",
45
+ LAST_NODE_COUNTER: 0
46
+ },
47
+ schema: null,
48
+ schemaCustomization: {
49
+ types: [],
50
+ fieldExtensions: {},
51
+ thirdPartySchemas: [],
52
+ printConfig: null,
53
+ context: {},
54
+ composer: null
55
+ },
56
+ inferenceMetadata: {
57
+ step: "initialBuild",
58
+ typeMap: {}
59
+ },
60
+ webpack: {},
61
+ babelrc: { stages: {} },
62
+ jobsV2: {
63
+ incomplete: /* @__PURE__ */ new Map(),
64
+ complete: /* @__PURE__ */ new Map()
65
+ },
66
+ requestHeaders: /* @__PURE__ */ new Map(),
67
+ statefulSourcePlugins: /* @__PURE__ */ new Set(),
68
+ nodesTouched: /* @__PURE__ */ new Set()
69
+ };
70
+ }
71
+ export { initialState };
@@ -0,0 +1,124 @@
1
+ import { setRendererNodeHooks } from "./compat/module-hooks.js";
2
+ import { importModule } from "./loader/import-module.js";
3
+ import { resolveModule } from "./utils/resolver.js";
4
+ import { runtimeDir } from "./vite/paths.js";
5
+ import reporter from "./reporter.js";
6
+ import crypto from "node:crypto";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import v8 from "node:v8";
10
+ // src/node/renderer.ts
11
+ /** The reporter for renderers: bound methods, so they work detached. */
12
+ const rendererReporter = {
13
+ info: (message) => reporter.info(message),
14
+ warn: (message) => reporter.warn(message),
15
+ error: (message, error) => reporter.error(message, error),
16
+ verbose: (message) => reporter.verbose(message)
17
+ };
18
+ /** The built-in renderer: react-dom 18 or 19. */
19
+ const reactRenderer = {
20
+ name: "react",
21
+ runtime: {
22
+ shared: path.join(runtimeDir, "renderers", "react.js"),
23
+ server: path.join(runtimeDir, "renderers", "react-server.js"),
24
+ client: path.join(runtimeDir, "renderers", "react-client.js")
25
+ },
26
+ vite: ({ isBuild }) => ({
27
+ dedupe: ["react", "react-dom"],
28
+ ssrExternal: isBuild ? [
29
+ "react",
30
+ "react-dom",
31
+ "react-dom/server",
32
+ "react/jsx-runtime",
33
+ "react/jsx-dev-runtime"
34
+ ] : void 0
35
+ })
36
+ };
37
+ /** Problems of a `renderer` option in gatsby-config (empty when it is valid). */
38
+ function validateRendererConfig(value) {
39
+ if (value === void 0) return [];
40
+ if (!value || typeof value !== "object" || Array.isArray(value)) return ["\"renderer\" must be an object: { name, module, options? } (what a renderer package's function returns)"];
41
+ const { name, module, options } = value;
42
+ const problems = [];
43
+ if (typeof name !== "string" || !name) problems.push("\"renderer.name\" must be a string");
44
+ if (typeof module !== "string" || !module) problems.push("\"renderer.module\" must be a string");
45
+ try {
46
+ v8.serialize(options);
47
+ } catch (e) {
48
+ problems.push(`"renderer.options" must be plain data that worker threads can receive (no functions or class instances): ${e.message}`);
49
+ }
50
+ return problems;
51
+ }
52
+ /** The descriptor with `module` as an absolute path, so that any thread can import it. */
53
+ async function resolveRendererDescriptor(descriptor, root) {
54
+ let file;
55
+ if (descriptor.module.startsWith("file:")) file = fileURLToPath(descriptor.module);
56
+ else if (path.isAbsolute(descriptor.module)) file = descriptor.module;
57
+ else if (descriptor.module.startsWith(".")) file = path.resolve(root, descriptor.module);
58
+ else try {
59
+ file = resolveModule(descriptor.module, root);
60
+ } catch (e) {
61
+ throw new Error(`The renderer "${descriptor.name}" (gatsby-config "renderer") was not found: cannot resolve "${descriptor.module}" from ${root}`, { cause: e });
62
+ }
63
+ return {
64
+ ...descriptor,
65
+ module: file
66
+ };
67
+ }
68
+ let current = reactRenderer;
69
+ let currentDescriptor;
70
+ /** identity of the loaded renderer: resolved descriptor and site root */
71
+ let currentKey;
72
+ /** The renderer of this thread (the built-in one until `useRenderer` loaded another). */
73
+ function getRenderer() {
74
+ return current;
75
+ }
76
+ /**
77
+ * Identifies what renders the HTML, for the HTML cache key: the resolved descriptor (module and
78
+ * options) and the renderer's own `cacheKey`.
79
+ */
80
+ function getRendererFingerprint() {
81
+ if (!currentDescriptor) return current.name;
82
+ return crypto.createHash("sha256").update(v8.serialize(currentDescriptor)).update(String(current.cacheKey ?? "")).digest("hex");
83
+ }
84
+ /** The resolved `renderer` option, for worker threads (undefined with the built-in renderer). */
85
+ function getRendererDescriptor() {
86
+ return currentDescriptor;
87
+ }
88
+ /**
89
+ * Loads the renderer of a `renderer` option and registers its Node hooks in this thread. Without
90
+ * a descriptor the built-in renderer is used, which needs neither.
91
+ */
92
+ async function useRenderer(descriptor, root) {
93
+ if (!descriptor) {
94
+ current = reactRenderer;
95
+ currentDescriptor = void 0;
96
+ currentKey = void 0;
97
+ setRendererNodeHooks(void 0);
98
+ return current;
99
+ }
100
+ const resolved = await resolveRendererDescriptor(descriptor, root);
101
+ const key = crypto.createHash("sha256").update(v8.serialize({
102
+ ...resolved,
103
+ root
104
+ })).digest("hex");
105
+ if (key === currentKey) return current;
106
+ const mod = await importModule(resolved.module);
107
+ const factory = mod.default?.default ?? mod.default;
108
+ if (typeof factory !== "function") throw new Error(`The renderer "${descriptor.name}" (${resolved.module}) has no default export that is a function`);
109
+ const renderer = await factory(structuredClone(resolved.options), {
110
+ root,
111
+ reporter: rendererReporter
112
+ });
113
+ for (const key of [
114
+ "shared",
115
+ "server",
116
+ "client"
117
+ ]) if (typeof renderer?.runtime?.[key] !== "string") throw new Error(`The renderer "${descriptor.name}" (${resolved.module}) must return runtime.${key}: the path of a module`);
118
+ setRendererNodeHooks(renderer.nodeHooks);
119
+ current = renderer;
120
+ currentDescriptor = resolved;
121
+ currentKey = key;
122
+ return renderer;
123
+ }
124
+ export { getRenderer, getRendererDescriptor, getRendererFingerprint, reactRenderer, resolveRendererDescriptor, useRenderer, validateRendererConfig };
@@ -0,0 +1,259 @@
1
+ import pc from "picocolors";
2
+ // src/node/reporter-transports.ts
3
+ /** as wide as the "success " label of the parent line */
4
+ const PART_INDENT = " ".repeat(8);
5
+ /** tree connectors of the parts below their parent line */
6
+ const PART_BRANCH = "├─ ";
7
+ const PART_LAST = "└─ ";
8
+ const LABELS = {
9
+ error: (c) => c.red("error"),
10
+ warn: (c) => c.yellow("warn"),
11
+ info: (c) => c.blue("info"),
12
+ success: (c) => c.green("success"),
13
+ verbose: (c) => c.gray("verbose"),
14
+ log: () => ""
15
+ };
16
+ /** Human readable output as printed by default (Gatsby style). */
17
+ function consoleTransport(options = {}) {
18
+ const colors = options.colors === void 0 ? pc : pc.createColors(options.colors);
19
+ /** the parts of an activity printed so far, by the parent's id (until its last part) */
20
+ const pendingParts = /* @__PURE__ */ new Map();
21
+ return { log(entry) {
22
+ if ((options.silent ?? !!process.env.GOATLY_SILENT) && entry.level !== "error") return;
23
+ const out = entry.level === "error" || entry.level === "warn" ? options.stderr ?? process.stderr : options.stdout ?? process.stdout;
24
+ let text = entry.text;
25
+ if (entry.level === "error" && entry.error?.stack) text += `\n\n${colors.gray(entry.error.stack.split("\n").slice(1, 12).join("\n"))}`;
26
+ if (entry.activity?.parentId) {
27
+ const parentId = entry.activity.parentId;
28
+ const parts = pendingParts.get(parentId) ?? [];
29
+ parts.push(entry);
30
+ if (!entry.activity.lastPart) return void pendingParts.set(parentId, parts);
31
+ pendingParts.delete(parentId);
32
+ const withSpans = parts.filter((p) => p.activity.span);
33
+ const bars = layoutBars(withSpans.map((p) => [p.activity.span]), PART_BAR_WIDTH);
34
+ let lines = "";
35
+ for (const part of parts) {
36
+ const i = withSpans.indexOf(part);
37
+ const branch = colors.gray(part.activity.lastPart ? PART_LAST : PART_BRANCH);
38
+ const bar = i >= 0 ? `${drawBar(bars[i], PART_BAR_WIDTH, colors, "cyan")} ` : "";
39
+ lines += `${PART_INDENT}${branch}${bar}${part.text}\n`;
40
+ }
41
+ out.write(lines);
42
+ return;
43
+ }
44
+ if (entry.breakdown) text = formatTimingBreakdown(entry.breakdown.segments, {
45
+ colors,
46
+ title: entry.breakdown.title
47
+ });
48
+ const label = LABELS[entry.level](colors);
49
+ out.write(`${label ? `${label} ` : ""}${text}\n`);
50
+ } };
51
+ }
52
+ /** bar colors per segment position */
53
+ const SEGMENT_COLORS = [
54
+ "cyan",
55
+ "blue",
56
+ "magenta",
57
+ "yellow",
58
+ "green",
59
+ "red",
60
+ "white",
61
+ "gray"
62
+ ];
63
+ const BAR = "█";
64
+ const TRACK = "-";
65
+ /** characters of the timeline of an activity's parts */
66
+ const PART_BAR_WIDTH = 20;
67
+ /**
68
+ * Lays out bars on a timeline of `width` cells. Each row has one or more spans ([start, end] as
69
+ * fractions of the timeline, 0–1). A span with time gets at least one cell, and two spans share
70
+ * cells only if they overlap in time: one that starts when (or after) another ended is drawn
71
+ * after it, also when rounding would put them in the same cell.
72
+ */
73
+ function layoutBars(rows, width) {
74
+ const clamp = (x) => Math.min(1, Math.max(0, x));
75
+ const spans = rows.flatMap((row, r) => row.map(([s, e]) => {
76
+ const start = clamp(s);
77
+ const end = Math.max(start, clamp(e));
78
+ return {
79
+ r,
80
+ start,
81
+ end,
82
+ from: Math.round(start * width),
83
+ to: Math.round(end * width)
84
+ };
85
+ }));
86
+ const after = (b, a) => a !== b && a.end > a.start && b.start >= a.end - 1e-9;
87
+ const order = [...spans].sort((a, b) => a.start - b.start || a.end - b.end);
88
+ for (const span of order) {
89
+ for (const a of order) if (after(span, a)) span.from = Math.max(span.from, a.to);
90
+ span.to = Math.max(span.to, span.from + (span.end > span.start ? 1 : 0));
91
+ }
92
+ for (const span of order.toReversed()) {
93
+ let limit = width;
94
+ for (const b of order) if (after(b, span)) limit = Math.min(limit, b.from);
95
+ span.to = Math.min(span.to, limit);
96
+ span.from = Math.max(0, Math.min(span.from, span.to - (span.end > span.start ? 1 : 0)));
97
+ }
98
+ return rows.map((_, r) => spans.filter((s) => s.r === r).map((s) => [s.from, s.to]));
99
+ }
100
+ /** a row of a timeline: `-----██████---------` (the bars' cells in `color`) */
101
+ function drawBar(bars, width, colors, color) {
102
+ const filled = Array.from({ length: width }, () => false);
103
+ for (const [from, to] of bars) for (let c = from; c < to; c++) filled[c] = true;
104
+ const paint = colors[color];
105
+ let out = "";
106
+ for (let c = 0; c < width;) {
107
+ let n = c;
108
+ while (n < width && filled[n] === filled[c]) n++;
109
+ const run = (filled[c] ? BAR : TRACK).repeat(n - c);
110
+ out += filled[c] ? paint(run) : colors.gray(run);
111
+ c = n;
112
+ }
113
+ return out;
114
+ }
115
+ /**
116
+ * The breakdown of a line's time as a Gantt chart: one row per segment (as a tree below the line,
117
+ * like the parts of an activity) with its time, its share and its bars on a timeline. Without
118
+ * `spans`, the segments follow one another, each bar starts where the previous one ended:
119
+ *
120
+ * ```
121
+ * Done building 120 pages in 4.21s
122
+ * ├─ bootstrap 1.203s 29% ███████████-----------------------------
123
+ * ├─ run static queries 0.301s 7% -----------███--------------------------
124
+ * ├─ run page queries 2.650s 63% --------------█████████████████████████-
125
+ * └─ save caches and state 0.050s <1% ---------------------------------------█
126
+ * ```
127
+ *
128
+ * With `spans`, segments that ran at the same time overlap (their shares then add up to more than
129
+ * 100%). A segment with time gets at least one cell; segments without time are dimmed.
130
+ */
131
+ function formatTimingBreakdown(segments, options = {}) {
132
+ const colors = typeof options.colors === "object" ? options.colors : pc.createColors(!!options.colors);
133
+ const width = Math.max(1, options.width ?? 40);
134
+ let elapsed = 0;
135
+ const timed = segments.some((s) => s.spans);
136
+ const spans = segments.map((s) => {
137
+ if (timed) return (s.spans ?? []).filter(([a, b]) => b > a);
138
+ const ms = Math.max(0, s.ms);
139
+ elapsed += ms;
140
+ return ms > 0 ? [[elapsed - ms, elapsed]] : [];
141
+ });
142
+ const total = Math.max(0, ...spans.flat().map(([, end]) => end));
143
+ const labelWidth = Math.max(...segments.map((s) => s.label.length), 0);
144
+ const times = segments.map((s) => `${(s.ms / 1e3).toFixed(3)}s`);
145
+ const timeWidth = Math.max(...times.map((t) => t.length), 0);
146
+ const shares = segments.map((s) => {
147
+ const percent = total > 0 ? Math.max(0, s.ms) / total * 100 : 0;
148
+ return percent > 0 && percent < .5 ? "<1%" : `${Math.round(percent)}%`;
149
+ });
150
+ const shareWidth = Math.max(...shares.map((s) => s.length), 0);
151
+ const bars = layoutBars(spans.map((row) => total > 0 ? row.map(([a, b]) => [a / total, b / total]) : []), width);
152
+ const rows = segments.map((s, i) => {
153
+ const timeline = drawBar(bars[i], width, colors, SEGMENT_COLORS[i % SEGMENT_COLORS.length]);
154
+ const text = `${s.label.padEnd(labelWidth)} ${times[i].padStart(timeWidth)} ${shares[i].padStart(shareWidth)}`;
155
+ return `${colors.gray(i === segments.length - 1 ? PART_LAST : PART_BRANCH)}${s.ms > 0 ? text : colors.dim(text)} ${timeline}`;
156
+ });
157
+ return [options.title ?? "timing breakdown", ...rows].join(`\n${PART_INDENT}`);
158
+ }
159
+ /** One JSON object per line – for CI systems and log shippers. */
160
+ function jsonTransport(options = {}) {
161
+ const write = (value) => (options.stream ?? process.stdout).write(`${JSON.stringify(value)}\n`);
162
+ return {
163
+ log: (entry) => write({
164
+ type: "log",
165
+ ...entry
166
+ }),
167
+ activityStart: options.activityEvents ? (activity) => write({
168
+ type: "activityStart",
169
+ timestamp: Date.now(),
170
+ activity
171
+ }) : void 0,
172
+ activityUpdate: options.activityEvents ? (activity) => write({
173
+ type: "activityUpdate",
174
+ timestamp: Date.now(),
175
+ activity
176
+ }) : void 0,
177
+ activityEnd: (activity) => write({
178
+ type: "activityEnd",
179
+ timestamp: Date.now(),
180
+ activity
181
+ })
182
+ };
183
+ }
184
+ function detectStyle(logger) {
185
+ const l = logger;
186
+ if (typeof l.bindings === "function" && l.levels?.values) return "object-first";
187
+ if (Array.isArray(l.streams) && l.fields && typeof l.fields === "object") return "object-first";
188
+ return "message-first";
189
+ }
190
+ /** structured data of an entry (without undefined values) */
191
+ function metaOf(entry) {
192
+ const meta = {};
193
+ if (entry.error) meta.error = entry.error;
194
+ if (entry.activity) meta.activity = entry.activity;
195
+ if (entry.threadId !== void 0) meta.threadId = entry.threadId;
196
+ return Object.keys(meta).length ? meta : void 0;
197
+ }
198
+ /**
199
+ * Sends all reporter output to an existing logger, e.g.
200
+ *
201
+ * ```ts
202
+ * import winston from "winston"
203
+ * import { loggerTransport } from "gatsby/reporter"
204
+ * reporter: loggerTransport(winston.createLogger({ transports: [new winston.transports.Console()] }))
205
+ * ```
206
+ */
207
+ function loggerTransport(logger, options = {}) {
208
+ const style = options.style ?? detectStyle(logger);
209
+ const fn = (name, fallback) => {
210
+ const candidate = name ? logger[name] : void 0;
211
+ return (typeof candidate === "function" ? candidate : logger[fallback]).bind(logger);
212
+ };
213
+ const verbose = fn(options.verboseLevel ?? (typeof logger.verbose === "function" ? "verbose" : "debug"), typeof logger.debug === "function" ? "debug" : "info");
214
+ const methods = {
215
+ error: fn("error", "info"),
216
+ warn: fn("warn", "info"),
217
+ info: fn("info", "info"),
218
+ log: fn("info", "info"),
219
+ success: fn(options.successLevel, "info"),
220
+ verbose
221
+ };
222
+ const emit = (level, text, meta) => {
223
+ const method = methods[level];
224
+ if (!meta) method(text);
225
+ else if (style === "object-first") method(meta, text);
226
+ else method(text, meta);
227
+ };
228
+ return {
229
+ log(entry) {
230
+ emit(entry.level, entry.text, metaOf(entry));
231
+ },
232
+ activityStart: options.activityStarts ? (activity) => emit("verbose", `${activity.text} started`, { activity }) : void 0,
233
+ activityEnd(activity) {
234
+ const text = activityEndText(activity);
235
+ emit(activity.outcome === "failed" ? "error" : "success", text, { activity });
236
+ }
237
+ };
238
+ }
239
+ /**
240
+ * A rough average speed, as Gatsby shows it: "142/s" (whole numbers from 10/s, two significant
241
+ * digits below, e.g. "8.5/s", "0.47/s"). Empty when nothing was done or no time measured.
242
+ */
243
+ function formatRate(count, seconds) {
244
+ if (!(seconds > 0) || !(count > 0)) return "";
245
+ const perSecond = count / seconds;
246
+ return `${perSecond >= 10 ? Math.round(perSecond) : Number(perSecond.toPrecision(2))}/s`;
247
+ }
248
+ /** "build schema - 0.123s - 12 nodes" */
249
+ function activityEndText(activity) {
250
+ let text = `${activity.text} - ${activity.elapsed.toFixed(3)}s`;
251
+ if (activity.share !== void 0) text += ` (${Math.round(activity.share * 100)}%)`;
252
+ if (activity.type === "progress") {
253
+ const rate = formatRate(activity.current ?? 0, activity.elapsed);
254
+ text += ` - ${activity.current ?? 0}/${activity.total ?? 0}${rate ? ` ${rate}` : ""}`;
255
+ }
256
+ if (activity.status) text += ` - ${activity.status}`;
257
+ return text;
258
+ }
259
+ export { activityEndText, consoleTransport, formatRate, formatTimingBreakdown, jsonTransport, layoutBars, loggerTransport };