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,41 @@
1
+ // src/node/utils/serializable.ts
2
+ /**
3
+ * How values are prepared before they are stored (nodes in createNode / createNodeField, plugin
4
+ * cache values in `cache.set`): values without functions, symbols or cycles are stored as they are,
5
+ * others are copied without them first, like in Gatsby.
6
+ */
7
+ /**
8
+ * Whether a value has no function, symbol or cycle. Maps, Sets and binary data aren't looked into.
9
+ */
10
+ function isSerializable(value, seen = /* @__PURE__ */ new Set()) {
11
+ if (value === null) return true;
12
+ const t = typeof value;
13
+ if (t === "function" || t === "symbol") return false;
14
+ if (t !== "object") return true;
15
+ if (seen.has(value)) return false;
16
+ if (value instanceof Date || value instanceof RegExp) return true;
17
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;
18
+ seen.add(value);
19
+ for (const v of Array.isArray(value) ? value : Object.values(value)) if (v !== void 0 && !isSerializable(v, seen)) return false;
20
+ seen.delete(value);
21
+ return true;
22
+ }
23
+ /**
24
+ * A copy without functions and symbols (`undefined` for such a value itself). An object that occurs
25
+ * a second time (a cycle or a shared reference) is dropped, and objects other than arrays, `Date`,
26
+ * `RegExp` and `Buffer` become plain objects of their own enumerable fields.
27
+ */
28
+ function sanitize(value, seen = /* @__PURE__ */ new WeakSet()) {
29
+ if (value === null || typeof value !== "object") return typeof value === "function" || typeof value === "symbol" ? void 0 : value;
30
+ if (value instanceof Date || value instanceof RegExp || Buffer.isBuffer(value)) return value;
31
+ if (seen.has(value)) return void 0;
32
+ seen.add(value);
33
+ if (Array.isArray(value)) return value.map((v) => sanitize(v, seen));
34
+ const out = {};
35
+ for (const [k, v] of Object.entries(value)) {
36
+ const s = sanitize(v, seen);
37
+ if (s !== void 0) out[k] = s;
38
+ }
39
+ return out;
40
+ }
41
+ export { isSerializable, sanitize };
@@ -0,0 +1,41 @@
1
+ import { isBun } from "./runtime.js";
2
+ // src/node/utils/strings.ts
3
+ /**
4
+ * Strings that msgpackr decodes from nodes are slices of larger strings: its native string
5
+ * extractor (msgpackr-extract, loaded on Node and on Bun) decodes a run of a record's short ASCII
6
+ * strings as one string of up to 6,000 characters and hands out slices of it. V8 keeps a slice of 13
7
+ * or more characters as a reference to that string, JavaScriptCore every substring of 3 or more
8
+ * characters. A structure that outlives the node and keeps one of its strings (an id, a date, a
9
+ * slug) keeps the whole run alive: 1–6 KB per node instead of a few dozen bytes.
10
+ */
11
+ const SHARED_FROM = isBun ? 3 : 13;
12
+ /** (V8: see detachString) */
13
+ const internTable = Object.create(null);
14
+ /**
15
+ * `value` without the memory of the string it came from (for strings kept longer than the node they
16
+ * were read from, e.g. the query engine's views and indexes). V8: a property lookup internalizes its
17
+ * key, turning a slice into a reference to a flat copy in the string table, which equal strings
18
+ * share (a type's views and indexes keep the same ids and values many times; 35% less heap kept
19
+ * after the page queries of 200k posts than with a copy of each). JavaScriptCore keeps the base of
20
+ * a slice it atomizes, and of a slice of a new string: a JSON round trip copies.
21
+ */
22
+ const detachString = isBun ? (value) => value.length < SHARED_FROM ? value : JSON.parse(JSON.stringify(value)) : (value) => {
23
+ if (value.length >= SHARED_FROM) Reflect.has(internTable, value);
24
+ return value;
25
+ };
26
+ /**
27
+ * A copy of plain data (strings, arrays, plain objects) whose strings share no memory with the ones
28
+ * it came from (see detachString). Other objects (Dates, Buffers, class instances) are kept as they
29
+ * are.
30
+ */
31
+ function detachValue(value, depth = 0) {
32
+ if (typeof value === "string") return detachString(value);
33
+ if (value === null || typeof value !== "object" || depth > 64) return value;
34
+ if (Array.isArray(value)) return value.map((v) => detachValue(v, depth + 1));
35
+ const proto = Object.getPrototypeOf(value);
36
+ if (proto !== Object.prototype && proto !== null) return value;
37
+ const out = {};
38
+ for (const key in value) out[key] = detachValue(value[key], depth + 1);
39
+ return out;
40
+ }
41
+ export { detachString, detachValue };
@@ -0,0 +1,289 @@
1
+ import { store } from "../redux/index.js";
2
+ import reporter from "../reporter.js";
3
+ import { apiRunnerNode } from "../api-runner.js";
4
+ import { VIRTUAL, goatlyVitePlugin } from "./plugin.js";
5
+ import { findStaticImageBabelPlugin, staticImagePlugin } from "./static-image.js";
6
+ import { findStyledComponentsBabelOptions, styledComponentsPlugin } from "./styled-components.js";
7
+ import { createReactCompilerTransform, resolveReactCompiler } from "./react-compiler.js";
8
+ import { clientEntry, routerIndex, runtimeDir, runtimeIndex, ssrEntry } from "./paths.js";
9
+ import { slash } from "../utils/paths.js";
10
+ import { proxyToVite } from "../config/index.js";
11
+ import { getRenderer } from "../renderer.js";
12
+ import { SSR_BUILD_DIR } from "../cache-layout.js";
13
+ import { nodeModulesPluginNames, nodeModulesPlugins, nonSourceNodeModulesRe } from "./source-files.js";
14
+ import { pluginCommonJsDeps } from "./plugin-deps.js";
15
+ import path from "node:path";
16
+ import { mergeConfig } from "vite";
17
+ import react from "@vitejs/plugin-react";
18
+ // src/node/vite/config.ts
19
+ /** Values exposed to the bundle like Gatsby's DefinePlugin globals. */
20
+ function getDefines(stage) {
21
+ const { config, program } = store.getState();
22
+ const prefixPaths = program.prefixPaths;
23
+ const basePath = prefixPaths && config.pathPrefix || "";
24
+ const assetPrefix = prefixPaths && config.assetPrefix || "";
25
+ const pathPrefix = assetPrefix ? `${assetPrefix}${basePath}` : basePath;
26
+ const defines = {
27
+ __PATH_PREFIX__: JSON.stringify(pathPrefix),
28
+ __BASE_PATH__: JSON.stringify(basePath),
29
+ __ASSET_PREFIX__: JSON.stringify(assetPrefix),
30
+ __TRAILING_SLASH__: JSON.stringify(config.trailingSlash),
31
+ __PREFETCH__: JSON.stringify(config.prefetch ?? "viewport"),
32
+ "process.env.BUILD_STAGE": JSON.stringify(stage),
33
+ "process.env.GATSBY_SLICES": JSON.stringify(false),
34
+ __DEV__: JSON.stringify(!stage.startsWith("build"))
35
+ };
36
+ for (const [key, value] of Object.entries(process.env)) if (key.startsWith("GATSBY_") && value !== void 0) defines[`process.env.${key}`] = JSON.stringify(value);
37
+ return defines;
38
+ }
39
+ /**
40
+ * Compatibility shim for `onCreateWebpackConfig`: plugins are called with webpack-like
41
+ * helpers and the parts of the config that have a Vite equivalent (resolve.alias,
42
+ * DefinePlugin definitions) are translated. Everything else is ignored.
43
+ */
44
+ async function runWebpackCompat(stage) {
45
+ if (store.getState().flattenedPlugins.filter((p) => p.nodeAPIs.includes("onCreateWebpackConfig")).length === 0) return {
46
+ alias: {},
47
+ define: {}
48
+ };
49
+ store.dispatch({
50
+ type: "REPLACE_WEBPACK_CONFIG",
51
+ payload: {}
52
+ });
53
+ const marker = (kind) => (...args) => ({
54
+ __goatlyWebpackPlugin: kind,
55
+ args
56
+ });
57
+ const rule = (kind) => (options = {}) => ({
58
+ __goatlyRule: kind,
59
+ options
60
+ });
61
+ const pluginsHelper = new Proxy({}, { get: (_t, kind) => marker(kind) });
62
+ const rulesHelper = new Proxy({}, { get: (_t, kind) => rule(kind) });
63
+ const loadersHelper = new Proxy({}, { get: (_t, kind) => (options) => ({
64
+ loader: kind,
65
+ options
66
+ }) });
67
+ const config = {
68
+ mode: stage.startsWith("build") ? "production" : "development",
69
+ resolve: {
70
+ alias: {},
71
+ extensions: []
72
+ },
73
+ module: { rules: [] },
74
+ plugins: []
75
+ };
76
+ await apiRunnerNode("onCreateWebpackConfig", {
77
+ stage,
78
+ getConfig: () => config,
79
+ rules: rulesHelper,
80
+ loaders: loadersHelper,
81
+ plugins: pluginsHelper
82
+ });
83
+ const webpack = store.getState().webpack;
84
+ const alias = {};
85
+ const define = {};
86
+ const rawAlias = webpack?.resolve?.alias;
87
+ if (rawAlias && typeof rawAlias === "object" && !Array.isArray(rawAlias)) {
88
+ for (const [k, v] of Object.entries(rawAlias)) if (typeof v === "string") alias[k.replace(/\$$/, "")] = v;
89
+ }
90
+ for (const p of webpack?.plugins ?? []) if (p?.__goatlyWebpackPlugin === "define" && p.args?.[0]) Object.assign(define, p.args[0]);
91
+ else if (p?.definitions) Object.assign(define, p.definitions);
92
+ const ignored = Object.keys(webpack ?? {}).filter((k) => !["resolve", "plugins"].includes(k));
93
+ if (ignored.length) reporter.verbose(`onCreateWebpackConfig: ignoring webpack-only settings (${ignored.join(", ")})`);
94
+ return {
95
+ alias,
96
+ define
97
+ };
98
+ }
99
+ async function runViteConfigApi(stage, base) {
100
+ const results = await apiRunnerNode("onCreateViteConfig", {
101
+ stage,
102
+ getConfig: () => base
103
+ });
104
+ let merged = base;
105
+ for (const r of results) if (r && typeof r === "object") merged = mergeConfig(merged, r);
106
+ return merged;
107
+ }
108
+ /** Aliases from onCreateWebpackConfig, except for specifiers the renderer provides. */
109
+ function webpackAliases(aliases, owned, rendererName) {
110
+ return Object.entries(aliases).filter(([find]) => {
111
+ if (!owned?.includes(find)) return true;
112
+ reporter.verbose(`onCreateWebpackConfig: ignoring the alias for "${find}" (the renderer "${rendererName}" provides it)`);
113
+ return false;
114
+ }).map(([find, replacement]) => ({
115
+ find,
116
+ replacement
117
+ }));
118
+ }
119
+ async function createViteConfig({ stage, ctx }) {
120
+ const { config, program } = store.getState();
121
+ const directory = program.directory;
122
+ const isBuild = stage.startsWith("build");
123
+ const isSSR = stage === "build-html" || stage === "develop-html";
124
+ const prefix = program.prefixPaths ? `${config.assetPrefix || ""}${config.pathPrefix || ""}` : "";
125
+ const webpackCompat = await runWebpackCompat(stage);
126
+ await apiRunnerNode("onCreateBabelConfig", { stage });
127
+ const styledComponentsBabel = findStyledComponentsBabelOptions(stage);
128
+ const staticImageBabel = findStaticImageBabelPlugin(stage);
129
+ const renderer = getRenderer();
130
+ const rendererConfig = await renderer.vite?.({
131
+ stage,
132
+ isBuild,
133
+ root: directory
134
+ }) ?? {};
135
+ const alias = [
136
+ {
137
+ find: /^gatsby$/,
138
+ replacement: runtimeIndex
139
+ },
140
+ {
141
+ find: /^gatsby-link$/,
142
+ replacement: runtimeIndex
143
+ },
144
+ {
145
+ find: /^gatsby-script$/,
146
+ replacement: runtimeIndex
147
+ },
148
+ {
149
+ find: /^goatly$/,
150
+ replacement: runtimeIndex
151
+ },
152
+ {
153
+ find: /^@reach\/router$/,
154
+ replacement: routerIndex
155
+ },
156
+ {
157
+ find: /^@gatsbyjs\/reach-router$/,
158
+ replacement: routerIndex
159
+ },
160
+ {
161
+ find: /^goatly\/router$/,
162
+ replacement: routerIndex
163
+ },
164
+ {
165
+ find: /^(?:goatly|gatsby)\/runtime\/(.+?)(?:\.js)?$/,
166
+ replacement: `${slash(runtimeDir)}/$1.js`
167
+ },
168
+ ...webpackAliases(webpackCompat.alias, rendererConfig.ownedSpecifiers, renderer.name)
169
+ ];
170
+ const dirRe = (dir) => new RegExp(`^${slash(dir).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`);
171
+ const runtimeRe = dirRe(runtimeDir);
172
+ const rendererRuntimeRes = [...new Set(Object.values(renderer.runtime).map((file) => path.dirname(file)))].map(dirRe);
173
+ const reactCompilerOptions = await resolveReactCompiler(stage, renderer.name);
174
+ const reactCompiler = reactCompilerOptions ? await createReactCompilerTransform(reactCompilerOptions, directory) : void 0;
175
+ const pluginDeps = isBuild ? void 0 : pluginCommonJsDeps(nodeModulesPlugins(), directory);
176
+ const reactPlugin = react({
177
+ jsxRuntime: config.jsxRuntime,
178
+ jsxImportSource: config.jsxImportSource,
179
+ include: /\.(mdx|[jt]sx?|mjs)$/,
180
+ exclude: [
181
+ /\/node_modules\//,
182
+ runtimeRe,
183
+ ...rendererRuntimeRes
184
+ ]
185
+ });
186
+ let viteConfig = {
187
+ configFile: false,
188
+ root: directory,
189
+ base: `${prefix}/`,
190
+ mode: isBuild ? "production" : "development",
191
+ publicDir: path.join(directory, "static"),
192
+ cacheDir: path.join(program.cacheDir, "vite"),
193
+ logLevel: process.env.GOATLY_VITE_LOG ? "info" : "warn",
194
+ clearScreen: false,
195
+ appType: "custom",
196
+ envPrefix: ["GATSBY_", "VITE_"],
197
+ define: {
198
+ ...getDefines(stage),
199
+ ...webpackCompat.define
200
+ },
201
+ resolve: {
202
+ alias,
203
+ dedupe: rendererConfig.dedupe
204
+ },
205
+ oxc: {
206
+ include: /\.(m?ts|[jt]sx)$/,
207
+ exclude: [nonSourceNodeModulesRe(), runtimeRe],
208
+ jsx: {
209
+ runtime: config.jsxRuntime === "classic" ? "classic" : "automatic",
210
+ importSource: config.jsxImportSource
211
+ }
212
+ },
213
+ plugins: [
214
+ ...staticImageBabel ? [staticImagePlugin(staticImageBabel)] : [],
215
+ goatlyVitePlugin({
216
+ ...ctx,
217
+ jsxRuntime: config.jsxRuntime,
218
+ jsxImportSource: config.jsxImportSource,
219
+ reactCompiler,
220
+ precompiledDirs: [runtimeRe, ...rendererRuntimeRes]
221
+ }),
222
+ ...styledComponentsBabel ? [styledComponentsPlugin(styledComponentsBabel)] : [],
223
+ reactPlugin,
224
+ ...rendererConfig.plugins ?? []
225
+ ],
226
+ optimizeDeps: {
227
+ exclude: [
228
+ "goatly",
229
+ "gatsby",
230
+ VIRTUAL.renderer,
231
+ VIRTUAL.rendererServer,
232
+ VIRTUAL.rendererClient,
233
+ ...nodeModulesPluginNames()
234
+ ],
235
+ entries: [],
236
+ include: pluginDeps
237
+ },
238
+ server: {
239
+ middlewareMode: true,
240
+ hmr: true,
241
+ watch: { ignored: [
242
+ "**/.cache/**",
243
+ "**/public/**",
244
+ "**/*.goatly-*.mjs"
245
+ ] },
246
+ proxy: stage === "develop" ? proxyToVite(config.proxy) : void 0
247
+ },
248
+ ssr: {
249
+ noExternal: isBuild ? true : nodeModulesPluginNames(),
250
+ external: rendererConfig.ssrExternal
251
+ },
252
+ build: isSSR ? {
253
+ ssr: ssrEntry,
254
+ outDir: path.join(program.cacheDir, SSR_BUILD_DIR),
255
+ emptyOutDir: true,
256
+ copyPublicDir: false,
257
+ minify: false,
258
+ sourcemap: false,
259
+ reportCompressedSize: false,
260
+ rolldownOptions: { output: {
261
+ format: "esm",
262
+ entryFileNames: "render-page.mjs",
263
+ chunkFileNames: "chunks/[name]-[hash].mjs"
264
+ } }
265
+ } : {
266
+ outDir: program.publicDir,
267
+ emptyOutDir: false,
268
+ manifest: true,
269
+ assetsDir: "assets",
270
+ sourcemap: false,
271
+ reportCompressedSize: false,
272
+ modulePreload: { polyfill: false },
273
+ rolldownOptions: { input: { app: clientEntry } }
274
+ }
275
+ };
276
+ if (config.vite) {
277
+ const user = typeof config.vite === "function" ? await config.vite({
278
+ command: isBuild ? "build" : "serve",
279
+ stage
280
+ }) : config.vite;
281
+ if (user) viteConfig = mergeConfig(viteConfig, user);
282
+ }
283
+ viteConfig = await runViteConfigApi(stage, viteConfig);
284
+ return viteConfig;
285
+ }
286
+ function pageComponentEntries() {
287
+ return [...store.getState().components.keys()].map((c) => slash(c.split("?")[0]));
288
+ }
289
+ export { createViteConfig, getDefines, pageComponentEntries };
@@ -0,0 +1,12 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ // src/node/vite/paths.ts
4
+ const here = path.dirname(fileURLToPath(import.meta.url));
5
+ /** `dist/` (or `src/` when running from source in tests) */
6
+ const packageSrcRoot = path.resolve(here, "../..");
7
+ const runtimeDir = path.join(packageSrcRoot, "runtime");
8
+ const clientEntry = path.join(runtimeDir, "client-entry.js");
9
+ const ssrEntry = path.join(runtimeDir, "ssr.js");
10
+ const runtimeIndex = path.join(runtimeDir, "index.js");
11
+ const routerIndex = path.join(runtimeDir, "router", "index.js");
12
+ export { clientEntry, packageSrcRoot, routerIndex, runtimeDir, runtimeIndex, ssrEntry };
@@ -0,0 +1,232 @@
1
+ import { isCommonJsSource } from "../plugins/static-exports.js";
2
+ import { parseSync, walk } from "../utils/parser.js";
3
+ import { slash } from "../utils/paths.js";
4
+ import { builtinModules } from "node:module";
5
+ import path from "node:path";
6
+ import fs from "node:fs";
7
+ // src/node/vite/plugin-deps.ts
8
+ /**
9
+ * The CommonJS packages that the browser entries of plugins installed from npm import, as entries
10
+ * for Vite's `optimizeDeps.include` (`"gatsby-plugin-image > prop-types"`).
11
+ *
12
+ * The dev server doesn't pre-bundle plugin packages (gatsby-browser files import their modules by
13
+ * path, and a pre-bundled copy would duplicate them, e.g. React contexts), and Vite doesn't
14
+ * discover what files in node_modules import. So the dependencies of what the site imports from a
15
+ * plugin package (e.g. `GatsbyImage` from gatsby-plugin-image) would be served unbundled, and
16
+ * CommonJS ones converted by goatly. Pre-bundled, Rolldown converts them, and Vite gives
17
+ * the plugins' imports of them its own CommonJS interop, as for the site's dependencies.
18
+ *
19
+ * Only a package's browser entry counts (its `browser` field, a `browser` condition in `exports`,
20
+ * or its `module` field), with what it imports from the package by relative path: not `main`,
21
+ * which is Node code in source, transformer and remark plugins. gatsby-browser files are left out:
22
+ * they are entries of Vite's dependency scan already. And only plugins that resolve from the site
23
+ * (`root`) to the same directory: Vite resolves the first part of a nested entry from there (a
24
+ * theme's plugins under pnpm don't).
25
+ */
26
+ function pluginCommonJsDeps(plugins, root) {
27
+ const include = [];
28
+ const skip = /* @__PURE__ */ new Set([
29
+ "gatsby",
30
+ "goatly",
31
+ ...plugins.map((p) => p.name)
32
+ ]);
33
+ for (const { name, dir } of plugins) {
34
+ const pkg = readJson(path.join(dir, "package.json"));
35
+ if (!pkg || !resolvesFromRoot(root, name, dir)) continue;
36
+ const entry = browserEntry(dir, pkg);
37
+ if (!entry) continue;
38
+ for (const spec of bareImports(dir, pkg, [entry])) if (!skip.has(packageName(spec)) && isCommonJsPackage(dir, spec)) include.push(`${name} > ${spec}`);
39
+ }
40
+ return include;
41
+ }
42
+ /** Whether the package `name` resolves from `root` (as Vite resolves it) to `dir`. */
43
+ function resolvesFromRoot(root, name, dir) {
44
+ for (let d = root;; d = path.dirname(d)) {
45
+ const candidate = path.join(d, "node_modules", name);
46
+ if (fs.existsSync(path.join(candidate, "package.json"))) try {
47
+ return slash(fs.realpathSync(candidate)) === slash(fs.realpathSync(dir));
48
+ } catch {
49
+ return false;
50
+ }
51
+ if (path.dirname(d) === d) return false;
52
+ }
53
+ }
54
+ /** The package's entry for the browser, when it has one apart from `main`. */
55
+ function browserEntry(dir, pkg) {
56
+ const exp = pkg.exports;
57
+ if (!(pkg.browser !== void 0 || typeof pkg.module === "string" || exp !== void 0 && JSON.stringify(exp).includes("\"browser\""))) return void 0;
58
+ const entry = packageEntry(dir, pkg);
59
+ return entry && isFile(entry) ? entry : void 0;
60
+ }
61
+ const JS_RE = /\.(m?[jt]sx?|cjs|cts)$/;
62
+ const BUILTINS = new Set(builtinModules);
63
+ /** The bare specifiers that `entries` and the package files they import import. */
64
+ function bareImports(dir, pkg, entries) {
65
+ const bare = /* @__PURE__ */ new Set();
66
+ const seen = /* @__PURE__ */ new Set();
67
+ const queue = [...entries];
68
+ while (queue.length) {
69
+ const file = queue.pop();
70
+ if (seen.has(file)) continue;
71
+ seen.add(file);
72
+ let code;
73
+ try {
74
+ code = fs.readFileSync(file, "utf8");
75
+ } catch {
76
+ continue;
77
+ }
78
+ for (const spec of importSpecifiers(file, code)) if (spec.startsWith(".") || spec.startsWith("/")) {
79
+ const target = resolveRelative(dir, pkg, file, spec);
80
+ if (target && JS_RE.test(target)) queue.push(target);
81
+ } else if (!spec.startsWith("node:") && !BUILTINS.has(spec) && !spec.includes(":")) bare.add(spec);
82
+ }
83
+ return bare;
84
+ }
85
+ /** The specifiers of a module's static and dynamic imports, re-exports and `require()` calls. */
86
+ function importSpecifiers(file, code) {
87
+ let program;
88
+ try {
89
+ const lang = /\.[mc]?tsx?$/.test(file) ? file.endsWith("x") ? "tsx" : "ts" : "jsx";
90
+ program = parseSync(file, code, {
91
+ lang,
92
+ sourceType: "unambiguous"
93
+ }).program;
94
+ } catch {
95
+ return [];
96
+ }
97
+ const specs = [];
98
+ const literal = (n) => n?.type === "Literal" && typeof n.value === "string" ? n.value : void 0;
99
+ walk(program, {
100
+ ImportDeclaration(n) {
101
+ if (n.importKind !== "type") specs.push(n.source.value);
102
+ },
103
+ ExportNamedDeclaration(n) {
104
+ if (n.source && n.exportKind !== "type") specs.push(n.source.value);
105
+ },
106
+ ExportAllDeclaration(n) {
107
+ if (n.exportKind !== "type") specs.push(n.source.value);
108
+ },
109
+ ImportExpression(n) {
110
+ const spec = literal(n.source);
111
+ if (spec) specs.push(spec);
112
+ },
113
+ CallExpression(n) {
114
+ const spec = n.callee?.type === "Identifier" && n.callee.name === "require" && literal(n.arguments[0]);
115
+ if (spec) specs.push(spec);
116
+ }
117
+ });
118
+ return specs;
119
+ }
120
+ const EXTENSIONS = [
121
+ "",
122
+ ".js",
123
+ ".mjs",
124
+ ".cjs",
125
+ ".jsx",
126
+ ".ts",
127
+ ".tsx",
128
+ "/index.js",
129
+ "/index.mjs"
130
+ ];
131
+ /** A relative import inside the package, with its `browser` field's replacements. */
132
+ function resolveRelative(dir, pkg, from, spec) {
133
+ const base = path.resolve(path.dirname(from), spec);
134
+ for (const ext of EXTENSIONS) {
135
+ const file = browserReplacement(dir, pkg, base + ext);
136
+ if (file && isFile(file)) return file;
137
+ }
138
+ }
139
+ function browserReplacement(dir, pkg, file) {
140
+ const map = pkg.browser;
141
+ if (!map || typeof map !== "object") return file;
142
+ const key = `./${slash(path.relative(dir, file))}`;
143
+ if (!(key in map)) return file;
144
+ const to = map[key];
145
+ return typeof to === "string" ? path.resolve(dir, to) : void 0;
146
+ }
147
+ /** The conditions Vite resolves `exports` with for the browser in develop. */
148
+ const CONDITIONS = [
149
+ "browser",
150
+ "development",
151
+ "module",
152
+ "import",
153
+ "default"
154
+ ];
155
+ function pickExport(value) {
156
+ if (typeof value === "string") return value;
157
+ if (Array.isArray(value)) {
158
+ for (const v of value) {
159
+ const picked = pickExport(v);
160
+ if (picked) return picked;
161
+ }
162
+ return;
163
+ }
164
+ if (value && typeof value === "object") {
165
+ for (const [key, v] of Object.entries(value)) if (CONDITIONS.includes(key)) {
166
+ const picked = pickExport(v);
167
+ if (picked) return picked;
168
+ }
169
+ }
170
+ }
171
+ /** The file Vite loads for `subpath` ("." for the package) of the package in `dir`, in the browser. */
172
+ function packageEntry(dir, pkg, subpath = ".") {
173
+ if (pkg.exports !== void 0) {
174
+ const exp = pkg.exports;
175
+ const hasSubpaths = exp && typeof exp === "object" && !Array.isArray(exp) && Object.keys(exp)[0]?.startsWith(".");
176
+ const target = pickExport(hasSubpaths ? exp[subpath] : subpath === "." ? exp : void 0);
177
+ if (target) return path.resolve(dir, target);
178
+ if (hasSubpaths) return void 0;
179
+ }
180
+ if (subpath !== ".") {
181
+ const base = path.resolve(dir, subpath);
182
+ for (const ext of EXTENSIONS) if (isFile(base + ext)) return base + ext;
183
+ return;
184
+ }
185
+ const field = [
186
+ typeof pkg.browser === "string" ? pkg.browser : void 0,
187
+ pkg.module,
188
+ pkg.main
189
+ ].find((f) => typeof f === "string");
190
+ const base = path.resolve(dir, field ?? "index.js");
191
+ for (const ext of EXTENSIONS) {
192
+ const file = browserReplacement(dir, pkg, base + ext);
193
+ if (file && isFile(file)) return file;
194
+ }
195
+ }
196
+ function packageName(spec) {
197
+ const parts = spec.split("/");
198
+ return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
199
+ }
200
+ /** Whether `spec` resolves (from the plugin in `fromDir`) to a CommonJS module in the browser. */
201
+ function isCommonJsPackage(fromDir, spec) {
202
+ const name = packageName(spec);
203
+ for (let d = fromDir;; d = path.dirname(d)) {
204
+ const dir = path.join(d, "node_modules", name);
205
+ const pkg = readJson(path.join(dir, "package.json"));
206
+ if (pkg) {
207
+ const entry = packageEntry(dir, pkg, spec === name ? "." : `./${spec.slice(name.length + 1)}`);
208
+ if (!entry || !JS_RE.test(entry)) return false;
209
+ try {
210
+ return isCommonJsSource(fs.readFileSync(entry, "utf8"));
211
+ } catch {
212
+ return false;
213
+ }
214
+ }
215
+ if (path.dirname(d) === d) return false;
216
+ }
217
+ }
218
+ function readJson(file) {
219
+ try {
220
+ return JSON.parse(fs.readFileSync(file, "utf8"));
221
+ } catch {
222
+ return;
223
+ }
224
+ }
225
+ function isFile(file) {
226
+ try {
227
+ return fs.statSync(file).isFile();
228
+ } catch {
229
+ return false;
230
+ }
231
+ }
232
+ export { pluginCommonJsDeps };