goatly 0.1.0 → 0.1.2

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 (161) hide show
  1. package/README.md +874 -1
  2. package/bin/goatly.js +99 -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 +569 -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 +763 -0
  18. package/dist/node/build/memory-governor.js +450 -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 +186 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +626 -0
  24. package/dist/node/build/query-workers.js +863 -0
  25. package/dist/node/build/render-thread.js +103 -0
  26. package/dist/node/build/render-worker.js +162 -0
  27. package/dist/node/build/state.js +24 -0
  28. package/dist/node/build/timing-breakdown.js +216 -0
  29. package/dist/node/build/work-clock.js +75 -0
  30. package/dist/node/build/worker-pool.js +242 -0
  31. package/dist/node/cache-layout.js +99 -0
  32. package/dist/node/cache.js +1430 -0
  33. package/dist/node/compat/chokidar-shim.js +148 -0
  34. package/dist/node/compat/core-utils-lmdb.js +145 -0
  35. package/dist/node/compat/create-node-id-shim.js +1 -0
  36. package/dist/node/compat/module-hooks.js +245 -0
  37. package/dist/node/compat/redux-shim.js +1 -0
  38. package/dist/node/config/index.js +162 -0
  39. package/dist/node/config/not-found-pages.js +95 -0
  40. package/dist/node/datastore/codec.js +144 -0
  41. package/dist/node/datastore/index.js +127 -0
  42. package/dist/node/datastore/logfile/cache.js +89 -0
  43. package/dist/node/datastore/logfile/index.js +1329 -0
  44. package/dist/node/datastore/logfile/record.js +71 -0
  45. package/dist/node/datastore/types.js +1 -0
  46. package/dist/node/develop/express-compat.js +207 -0
  47. package/dist/node/develop/graphiql.js +22 -0
  48. package/dist/node/develop/hydration-report.js +41 -0
  49. package/dist/node/develop/index.js +618 -0
  50. package/dist/node/develop/local-url.js +10 -0
  51. package/dist/node/develop/ssr-runner.js +66 -0
  52. package/dist/node/gql.js +5 -0
  53. package/dist/node/index.js +15 -0
  54. package/dist/node/info.js +270 -0
  55. package/dist/node/internal-plugins/data-bridge.js +196 -0
  56. package/dist/node/internal-plugins/page-creator.js +318 -0
  57. package/dist/node/loader/import-module.js +160 -0
  58. package/dist/node/node-helpers.js +66 -0
  59. package/dist/node/not-found-pages.js +220 -0
  60. package/dist/node/plugins/api-list.js +12 -0
  61. package/dist/node/plugins/load-plugins.js +427 -0
  62. package/dist/node/plugins/resolve-plugin.js +79 -0
  63. package/dist/node/plugins/static-exports.js +64 -0
  64. package/dist/node/query/compile.js +326 -0
  65. package/dist/node/query/dependencies.js +45 -0
  66. package/dist/node/query/execute.js +417 -0
  67. package/dist/node/query/extract.js +372 -0
  68. package/dist/node/query/gql-tada-introspection.js +124 -0
  69. package/dist/node/query/graphql-env.js +231 -0
  70. package/dist/node/query/graphql-runner.js +79 -0
  71. package/dist/node/redux/actions.js +1 -0
  72. package/dist/node/redux/index.js +133 -0
  73. package/dist/node/redux/node-changes.js +128 -0
  74. package/dist/node/redux/reducers.js +193 -0
  75. package/dist/node/redux/state.js +71 -0
  76. package/dist/node/renderer.js +124 -0
  77. package/dist/node/reporter-transports.js +259 -0
  78. package/dist/node/reporter.js +497 -0
  79. package/dist/node/schema/date.js +539 -0
  80. package/dist/node/schema/extensions.js +315 -0
  81. package/dist/node/schema/index.js +542 -0
  82. package/dist/node/schema/infer.js +388 -0
  83. package/dist/node/schema/inline-objects.js +128 -0
  84. package/dist/node/schema/naming.js +20 -0
  85. package/dist/node/schema/node-model.js +207 -0
  86. package/dist/node/schema/query-engine.js +1808 -0
  87. package/dist/node/schema/resolver-kinds.js +7 -0
  88. package/dist/node/schema/resolvers.js +273 -0
  89. package/dist/node/schema/type-builders.js +45 -0
  90. package/dist/node/schema/types.js +241 -0
  91. package/dist/node/serve.js +90 -0
  92. package/dist/node/site-page-nodes.js +277 -0
  93. package/dist/node/types.js +1 -0
  94. package/dist/node/utils/content-digest.js +107 -0
  95. package/dist/node/utils/cpus.js +104 -0
  96. package/dist/node/utils/create-node-id.js +51 -0
  97. package/dist/node/utils/env.js +25 -0
  98. package/dist/node/utils/fs-retry.js +74 -0
  99. package/dist/node/utils/memory-signals.js +441 -0
  100. package/dist/node/utils/memory.js +657 -0
  101. package/dist/node/utils/murmurhash.js +32 -0
  102. package/dist/node/utils/parser.js +33 -0
  103. package/dist/node/utils/partition-hash.js +19 -0
  104. package/dist/node/utils/paths.js +122 -0
  105. package/dist/node/utils/resolver.js +48 -0
  106. package/dist/node/utils/runtime.js +5 -0
  107. package/dist/node/utils/serializable.js +41 -0
  108. package/dist/node/utils/strings.js +41 -0
  109. package/dist/node/vite/config.js +289 -0
  110. package/dist/node/vite/paths.js +12 -0
  111. package/dist/node/vite/plugin-deps.js +232 -0
  112. package/dist/node/vite/plugin.js +283 -0
  113. package/dist/node/vite/react-compiler.js +362 -0
  114. package/dist/node/vite/source-files.js +83 -0
  115. package/dist/node/vite/static-image.js +136 -0
  116. package/dist/node/vite/styled-components.js +73 -0
  117. package/dist/node/vite/transforms.js +330 -0
  118. package/dist/node/wasm-data/host.js +406 -0
  119. package/dist/node/wasm-data/lower.js +406 -0
  120. package/dist/node/wasm-data/runner.js +79 -0
  121. package/dist/node/wasm-data/worker.js +95 -0
  122. package/dist/reporter.js +5 -0
  123. package/dist/runtime/api-runner.js +81 -0
  124. package/dist/runtime/app.js +256 -0
  125. package/dist/runtime/client-entry.js +4 -0
  126. package/dist/runtime/client.js +383 -0
  127. package/dist/runtime/default-html.js +31 -0
  128. package/dist/runtime/head-markup.js +100 -0
  129. package/dist/runtime/head-sync.js +101 -0
  130. package/dist/runtime/head-tags.js +45 -0
  131. package/dist/runtime/hydration-report.js +111 -0
  132. package/dist/runtime/index.js +12 -0
  133. package/dist/runtime/link.js +293 -0
  134. package/dist/runtime/loader.js +449 -0
  135. package/dist/runtime/not-found.js +61 -0
  136. package/dist/runtime/page-renderer.js +35 -0
  137. package/dist/runtime/preamble.js +47 -0
  138. package/dist/runtime/react-compat.js +14 -0
  139. package/dist/runtime/renderer-shared.js +10 -0
  140. package/dist/runtime/renderers/react-client.js +14 -0
  141. package/dist/runtime/renderers/react-server.js +99 -0
  142. package/dist/runtime/renderers/react.js +17 -0
  143. package/dist/runtime/renderers/types.js +1 -0
  144. package/dist/runtime/root-error-handlers.js +29 -0
  145. package/dist/runtime/router/history.js +132 -0
  146. package/dist/runtime/router/index.js +240 -0
  147. package/dist/runtime/router/utils.js +118 -0
  148. package/dist/runtime/script.js +110 -0
  149. package/dist/runtime/scroll.js +40 -0
  150. package/dist/runtime/slice.js +11 -0
  151. package/dist/runtime/ssr.js +240 -0
  152. package/dist/runtime/static-query.js +47 -0
  153. package/dist/utils.js +4 -0
  154. package/package.json +105 -3
  155. package/types/graphql-tada.d.ts +223 -0
  156. package/types/graphql.d.ts +2 -0
  157. package/types/index.d.ts +2287 -0
  158. package/types/node.d.ts +389 -0
  159. package/types/reporter.d.ts +187 -0
  160. package/types/router.d.ts +102 -0
  161. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,330 @@
1
+ import { extractFromSource } from "../query/extract.js";
2
+ import { getStaticExports } from "../plugins/static-exports.js";
3
+ import { parseSync, walk } from "../utils/parser.js";
4
+ import { slash } from "../utils/paths.js";
5
+ import path from "node:path";
6
+ import { MagicString } from "magic-string";
7
+ // src/node/vite/transforms.ts
8
+ /**
9
+ * Transforms `graphql` documents (tags and `graphql()` calls): static queries become imports of
10
+ * their result module, page queries and fragments are replaced by their hash. `exportsPageQuery`:
11
+ * the module exports a page query (which only runs if the module is a page component).
12
+ */
13
+ function transformGraphQLTags(code, id, opts) {
14
+ const file = id.split("?")[0];
15
+ const extraction = extractFromSource(file, code);
16
+ if (extraction.error || extraction.tags.length === 0) return null;
17
+ const s = new MagicString(code);
18
+ const imports = /* @__PURE__ */ new Set();
19
+ let exportsPageQuery = false;
20
+ for (const tag of extraction.tags) {
21
+ if (tag.kind === "page" && tag.exportName) exportsPageQuery = true;
22
+ if (extraction.tags.some((o) => o !== tag && o.start <= tag.start && tag.end <= o.end)) continue;
23
+ if (tag.kind === "static") {
24
+ const local = `__goatly_sq_${tag.hash}`;
25
+ imports.add(`import ${local} from ${JSON.stringify(`${opts.virtualPrefix}${tag.hash}`)};`);
26
+ s.overwrite(tag.start, tag.end, local);
27
+ } else s.overwrite(tag.start, tag.end, JSON.stringify(tag.hash));
28
+ }
29
+ s.prepend(`${[...imports].join("\n")}\n`);
30
+ return {
31
+ code: s.toString(),
32
+ map: s.generateMap({
33
+ hires: "boundary",
34
+ source: file
35
+ }),
36
+ exportsPageQuery
37
+ };
38
+ }
39
+ function langFor(file) {
40
+ const ext = path.extname(file);
41
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts") return "ts";
42
+ if (ext === ".tsx") return "tsx";
43
+ return "jsx";
44
+ }
45
+ /**
46
+ * Rewrites `<html ...>` / `<body ...>` JSX (used inside `Head` exports) to components that set
47
+ * document attributes. React 19 would otherwise treat them as document singletons, React 18 would
48
+ * render real `<html>`/`<body>` elements inside the Head container. Children of react-helmet's (or
49
+ * react-helmet-async's) `<Helmet>` stay: it reads them as props instead of rendering them.
50
+ */
51
+ function transformHtmlBodyJsx(code, id, headTagsModule) {
52
+ if (!/<(html|body)[\s/>]/.test(code)) return null;
53
+ const file = id.split("?")[0];
54
+ let program;
55
+ try {
56
+ program = parseSync(file, code, { lang: langFor(file) }).program;
57
+ } catch {
58
+ return null;
59
+ }
60
+ const s = new MagicString(code);
61
+ let changed = false;
62
+ const visit = (node) => {
63
+ if (!node || typeof node !== "object") return;
64
+ if (Array.isArray(node)) {
65
+ node.forEach(visit);
66
+ return;
67
+ }
68
+ if (node.type === "JSXElement" && node.openingElement?.name?.name === "Helmet") return;
69
+ if ((node.type === "JSXOpeningElement" || node.type === "JSXClosingElement") && node.name?.type === "JSXIdentifier") {
70
+ const name = node.name.name;
71
+ if (name === "html" || name === "body") {
72
+ s.overwrite(node.name.start, node.name.end, name === "html" ? "__GoatlyHtmlAttributes" : "__GoatlyBodyAttributes");
73
+ changed = true;
74
+ }
75
+ }
76
+ for (const key in node) {
77
+ if (key === "start" || key === "end" || key === "type") continue;
78
+ const v = node[key];
79
+ if (v && typeof v === "object") visit(v);
80
+ }
81
+ };
82
+ visit(program);
83
+ if (!changed) return null;
84
+ s.prepend(`import { HtmlAttributes as __GoatlyHtmlAttributes, BodyAttributes as __GoatlyBodyAttributes } from ${JSON.stringify(headTagsModule)};\n`);
85
+ return {
86
+ code: s.toString(),
87
+ map: s.generateMap({
88
+ hires: "boundary",
89
+ source: file
90
+ })
91
+ };
92
+ }
93
+ /**
94
+ * What `require(x)` returns, given `import * as ns from x` (CommonJS, ESM and asset modules).
95
+ * `"module.exports"` is not a named export: Node 24+ adds it to the namespace of every CommonJS
96
+ * module (the same value as `default`), so counting it made a `module.exports = function` with
97
+ * `__esModule` (Babel's `@babel/runtime` helpers) return the namespace instead of the function.
98
+ */
99
+ const REQUIRE_INTEROP = `function __goatly_interop(ns) { if (ns && ns.default !== undefined && Object.keys(ns).filter((k) => k !== "default" && k !== "__esModule" && k !== "module.exports").length === 0) return ns.default; return ns && ns.__esModule ? ns : (ns && ns.default && typeof ns.default === "object" ? Object.assign({}, ns.default, ns) : ns) }`;
100
+ /**
101
+ * Converts a CommonJS gatsby-browser / gatsby-ssr file (`exports.onRouteUpdate = ...`,
102
+ * `require("./global.css")`) into ESM so Vite can serve it unbundled in development. Export names
103
+ * found statically (`exports.a = `, `module.exports = { a, b }`) also become named exports, so
104
+ * ESM modules can `import { a } from` it, as with bundlers.
105
+ */
106
+ function transformCommonJsApiFile(code, file, defines) {
107
+ const named = file ? getStaticExports(file, code).filter((name) => /^[A-Za-z_$][\w$]*$/.test(name) && name !== "default" && name !== "__esModule") : [];
108
+ const calls = findStaticRequires(code, file ?? "module.cjs", "commonjs", defines);
109
+ if (!calls) return null;
110
+ const imports = [];
111
+ const s = new MagicString(code);
112
+ calls.forEach((call, i) => {
113
+ const local = `__goatly_req_${i}`;
114
+ imports.push(`import * as ${local}__ns from ${JSON.stringify(call.spec)};`);
115
+ imports.push(`const ${local} = __goatly_interop(${local}__ns);`);
116
+ s.overwrite(call.start, call.end, local);
117
+ });
118
+ return `${imports.join("\n")}
119
+ ${REQUIRE_INTEROP}
120
+ const module = { exports: {} };
121
+ (function (exports, module) {
122
+ ${s.toString()}
123
+ }).call(module.exports, module.exports, module);
124
+ export default module.exports;
125
+ ${named.map((name, i) => `const __goatly_export_${i} = module.exports[${JSON.stringify(name)}];`).join("\n")}
126
+ ${named.length ? `export { ${named.map((name, i) => `__goatly_export_${i} as ${name}`).join(", ")} };` : ""}
127
+ `;
128
+ }
129
+ /**
130
+ * Rewrites `require("x")` calls in an ES module (e.g. `import React from "react"` next to
131
+ * `require("./global.css")` or `const logo = require("./logo.png")`, which webpack accepted) to
132
+ * imports, so the module also runs unbundled in development, where `require` is not defined (in
133
+ * the browser and in Vite's SSR module runner). Only calls with a static string are rewritten; the
134
+ * imports are hoisted, so the required modules are evaluated before the module, not at the call.
135
+ * Scopes that bind `require` themselves are left alone.
136
+ */
137
+ function transformRequireInEsm(code, id, defines) {
138
+ if (!/\brequire\s*\(/.test(code)) return null;
139
+ const file = id.split("?")[0];
140
+ const calls = findStaticRequires(code, file, "module", defines);
141
+ if (!calls?.length) return null;
142
+ const s = new MagicString(code);
143
+ const locals = /* @__PURE__ */ new Map();
144
+ const imports = [];
145
+ for (const call of calls) {
146
+ let local = locals.get(call.spec);
147
+ if (!local) {
148
+ local = `__goatly_esm_req_${locals.size}`;
149
+ locals.set(call.spec, local);
150
+ imports.push(`import * as ${local}__ns from ${JSON.stringify(call.spec)};`);
151
+ imports.push(`const ${local} = __goatly_interop(${local}__ns);`);
152
+ }
153
+ s.overwrite(call.start, call.end, local);
154
+ }
155
+ s.prepend(`${imports.join("\n")}\n${REQUIRE_INTEROP}\n`);
156
+ return {
157
+ code: s.toString(),
158
+ map: s.generateMap({
159
+ hires: "boundary",
160
+ source: file
161
+ })
162
+ };
163
+ }
164
+ /**
165
+ * `import * as ns` of a converted CommonJS module, as Rolldown's `__toESM` builds it: the exports
166
+ * object of a transpiled ES module (`__esModule`), else `module.exports`' own properties (also
167
+ * non-enumerable ones, and its prototype's, e.g. a class instance's methods) plus `default`
168
+ */
169
+ const CJS_NAMESPACE = `function __goatly_cjs_ns(m) { if (m && m.__esModule) return m; if (m === null || (typeof m !== "object" && typeof m !== "function")) return { default: m }; const ns = Object.create(Object.getPrototypeOf(m)); for (const k of Object.getOwnPropertyNames(m)) if (k !== "default") Object.defineProperty(ns, k, { get: () => m[k], enumerable: true }); Object.defineProperty(ns, "default", { value: m, enumerable: true }); return ns }`;
170
+ /**
171
+ * Rewrites imports of CommonJS modules in an ES module served unbundled in development (the
172
+ * packages of plugins, which Vite does not pre-bundle, and their dependencies). The dev server
173
+ * converts those CommonJS modules to ESM with `module.exports` as the default export and only the
174
+ * export names it finds statically, so `import * as PropTypes from "prop-types"` (whose
175
+ * `module.exports` is a function call) would get only `default`, and `import { a } from` a name set
176
+ * dynamically would not link. Like webpack and Rolldown, a namespace import gets `module.exports`'
177
+ * properties plus `default`, named imports of names the module doesn't export statically read
178
+ * `module.exports`' properties, and the default import of a module compiled from ESM
179
+ * (`__esModule`) is `exports.default`. Only those bindings become constants (initialized where the
180
+ * import was); the others stay import bindings. `cjsExports(spec)`: `null` when `spec` doesn't
181
+ * resolve to such a CommonJS module.
182
+ */
183
+ async function transformCjsImportsInEsm(code, id, cjsExports) {
184
+ if (!/\bimport\s*(?:[\w$]+\s*(?:,|from\b)|[*{])/.test(code)) return null;
185
+ const file = id.split("?")[0];
186
+ let parsed;
187
+ try {
188
+ parsed = parseSync(file, code, {
189
+ lang: langFor(file),
190
+ sourceType: "module"
191
+ });
192
+ } catch {
193
+ return null;
194
+ }
195
+ if (parsed.errors?.length) return null;
196
+ const s = new MagicString(code);
197
+ const importedName = (sp) => sp.imported.name ?? sp.imported.value;
198
+ let changed = false;
199
+ for (const [i, stmt] of parsed.program.body.entries()) {
200
+ if (stmt.type !== "ImportDeclaration" || stmt.importKind === "type") continue;
201
+ const specifiers = stmt.specifiers.filter((sp) => sp.importKind !== "type");
202
+ const namespace = specifiers.find((sp) => sp.type === "ImportNamespaceSpecifier");
203
+ const defaults = specifiers.filter((sp) => sp.type === "ImportDefaultSpecifier" || sp.type === "ImportSpecifier" && importedName(sp) === "default");
204
+ const named = specifiers.filter((sp) => sp.type === "ImportSpecifier" && importedName(sp) !== "default");
205
+ if (!namespace && !named.length && !defaults.length) continue;
206
+ const target = await cjsExports(stmt.source.value);
207
+ if (!target) continue;
208
+ const dynamic = named.filter((sp) => !target.names.includes(importedName(sp)));
209
+ if (!namespace && !dynamic.length && !(target.esModule && defaults.length)) continue;
210
+ const liveDefault = !target.esModule && defaults.find((sp) => sp.type === "ImportDefaultSpecifier");
211
+ const local = liveDefault ? liveDefault.local.name : `__goatly_cjs_${i}`;
212
+ const kept = named.filter((sp) => !dynamic.includes(sp));
213
+ if (!target.esModule) kept.push(...defaults.filter((sp) => sp !== liveDefault));
214
+ const keptList = kept.map((sp) => importedName(sp) === sp.local.name ? sp.local.name : `${JSON.stringify(importedName(sp))} as ${sp.local.name}`);
215
+ let out = `import ${local}${keptList.length ? `, { ${keptList.join(", ")} }` : ""} from ${JSON.stringify(stmt.source.value)};`;
216
+ if (target.esModule) for (const sp of defaults) out += ` const ${sp.local.name} = ${local}.default;`;
217
+ if (namespace) out += ` const ${namespace.local.name} = __goatly_cjs_ns(${local});`;
218
+ if (dynamic.length) {
219
+ const fields = dynamic.map((sp) => `${JSON.stringify(importedName(sp))}: ${sp.local.name}`);
220
+ out += ` const { ${fields.join(", ")} } = ${local};`;
221
+ }
222
+ s.overwrite(stmt.start, stmt.end, out);
223
+ changed = true;
224
+ }
225
+ if (!changed) return null;
226
+ s.append(`\n${CJS_NAMESPACE}\n`);
227
+ return {
228
+ code: s.toString(),
229
+ map: s.generateMap({
230
+ hires: "boundary",
231
+ source: file
232
+ })
233
+ };
234
+ }
235
+ const isRequireId = (n) => n?.type === "Identifier" && n.name === "require";
236
+ /**
237
+ * The `require("x")` calls with a static string (or a template literal without expressions) that
238
+ * refer to the global `require`, not to one a surrounding scope binds (a parameter, or a declaration
239
+ * in the function or file outside nested functions; block scoping is not distinguished). `null` if
240
+ * the code does not parse, or (for `"module"`) has no import/export statements.
241
+ *
242
+ * `require(NAME)` counts as static too when `defines` (Vite's `define`, which includes the
243
+ * DefinePlugin definitions of `onCreateWebpackConfig`) replaces `NAME` with a string. That is what
244
+ * gatsby-plugin-layout does: `require(GATSBY_LAYOUT_COMPONENT_PATH)`, with the path of the site's
245
+ * layout component defined in its `onCreateWebpackConfig`. webpack substitutes definitions before
246
+ * it resolves requires, and so does Rolldown in production builds; in develop the call is
247
+ * converted here, before Vite's define replacement runs, so the name is looked up here.
248
+ */
249
+ function findStaticRequires(code, file, sourceType, defines) {
250
+ let parsed;
251
+ try {
252
+ parsed = parseSync(file, code, {
253
+ lang: langFor(file),
254
+ sourceType
255
+ });
256
+ } catch {
257
+ return null;
258
+ }
259
+ if (parsed.errors?.length) return null;
260
+ if (sourceType === "module" && !parsed.module?.hasModuleSyntax) return null;
261
+ const program = parsed.program;
262
+ const binding = /* @__PURE__ */ new Set();
263
+ const scopes = [program];
264
+ const bind = (n) => isRequireId(n) && binding.add(scopes[scopes.length - 1]);
265
+ const enterFn = (fn) => {
266
+ scopes.push(fn);
267
+ if (fn.params.some(isRequireId)) binding.add(fn);
268
+ };
269
+ const exitFn = () => scopes.pop();
270
+ walk(program, {
271
+ FunctionDeclaration(fn) {
272
+ bind(fn.id);
273
+ enterFn(fn);
274
+ },
275
+ "FunctionDeclaration:exit": exitFn,
276
+ FunctionExpression: enterFn,
277
+ "FunctionExpression:exit": exitFn,
278
+ ArrowFunctionExpression: enterFn,
279
+ "ArrowFunctionExpression:exit": exitFn,
280
+ VariableDeclarator: (n) => bind(n.id),
281
+ ClassDeclaration: (n) => bind(n.id),
282
+ CatchClause: (n) => bind(n.param),
283
+ ImportSpecifier: (n) => bind(n.local),
284
+ ImportDefaultSpecifier: (n) => bind(n.local),
285
+ ImportNamespaceSpecifier: (n) => bind(n.local)
286
+ });
287
+ if (binding.has(program)) return [];
288
+ const calls = [];
289
+ let shadowed = 0;
290
+ const enter = (fn) => binding.has(fn) && shadowed++;
291
+ const exit = (fn) => binding.has(fn) && shadowed--;
292
+ walk(program, {
293
+ FunctionDeclaration: enter,
294
+ "FunctionDeclaration:exit": exit,
295
+ FunctionExpression: enter,
296
+ "FunctionExpression:exit": exit,
297
+ ArrowFunctionExpression: enter,
298
+ "ArrowFunctionExpression:exit": exit,
299
+ CallExpression(node) {
300
+ if (shadowed || !isRequireId(node.callee) || node.arguments.length !== 1) return;
301
+ const arg = node.arguments[0];
302
+ const spec = arg.type === "Literal" && typeof arg.value === "string" ? arg.value : arg.type === "TemplateLiteral" && arg.expressions.length === 0 ? arg.quasis[0].value.cooked : arg.type === "Identifier" ? definedString(defines, arg.name) : null;
303
+ if (spec != null) calls.push({
304
+ start: node.start,
305
+ end: node.end,
306
+ spec
307
+ });
308
+ }
309
+ });
310
+ return calls;
311
+ }
312
+ /**
313
+ * The string that `defines` replaces `name` with (a definition's value is code, e.g.
314
+ * `"\"/site/src/layout.js\""`), or null when `name` is not defined or not as a string literal. A
315
+ * local binding of the same name is not looked for: Vite's and webpack's define replace by name
316
+ * too, so such a module gets the definition in its other uses of the name as well. An absolute
317
+ * Windows path (`require.resolve()` in gatsby-config gives one) gets forward slashes, which is what
318
+ * Vite resolves as a file system path in an import.
319
+ */
320
+ function definedString(defines, name) {
321
+ if (!defines || !Object.hasOwn(defines, name)) return null;
322
+ try {
323
+ const value = JSON.parse(defines[name]);
324
+ if (typeof value !== "string") return null;
325
+ return /^[A-Za-z]:[\\/]/.test(value) ? slash(value) : value;
326
+ } catch {
327
+ return null;
328
+ }
329
+ }
330
+ export { transformCjsImportsInEsm, transformCommonJsApiFile, transformGraphQLTags, transformHtmlBodyJsx, transformRequireInEsm };