astro 4.7.0 → 4.8.0

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 (235) hide show
  1. package/client.d.ts +1 -0
  2. package/content-module.template.mjs +2 -0
  3. package/dist/@types/astro.d.ts +220 -4
  4. package/dist/actions/consts.d.ts +3 -0
  5. package/dist/actions/consts.js +8 -0
  6. package/dist/actions/index.d.ts +2 -0
  7. package/dist/actions/index.js +72 -0
  8. package/dist/actions/runtime/middleware.d.ts +7 -0
  9. package/dist/actions/runtime/middleware.js +38 -0
  10. package/dist/actions/runtime/route.d.ts +2 -0
  11. package/dist/actions/runtime/route.js +37 -0
  12. package/dist/actions/runtime/store.d.ts +6 -0
  13. package/dist/actions/runtime/store.js +18 -0
  14. package/dist/actions/runtime/utils.d.ts +4 -0
  15. package/dist/actions/runtime/utils.js +23 -0
  16. package/dist/actions/runtime/virtual/client.d.ts +4 -0
  17. package/dist/actions/runtime/virtual/client.js +20 -0
  18. package/dist/actions/runtime/virtual/server.d.ts +21 -0
  19. package/dist/actions/runtime/virtual/server.js +98 -0
  20. package/dist/actions/runtime/virtual/shared.d.ts +37 -0
  21. package/dist/actions/runtime/virtual/shared.js +104 -0
  22. package/dist/actions/utils.d.ts +2 -0
  23. package/dist/actions/utils.js +18 -0
  24. package/dist/assets/build/generate.js +1 -1
  25. package/dist/assets/internal.js +1 -2
  26. package/dist/assets/services/service.js +2 -4
  27. package/dist/assets/services/sharp.js +2 -4
  28. package/dist/assets/services/squoosh.js +2 -4
  29. package/dist/assets/services/vendor/squoosh/avif/avif_node_dec.js +34 -68
  30. package/dist/assets/services/vendor/squoosh/avif/avif_node_enc.js +39 -78
  31. package/dist/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_dec.js +32 -64
  32. package/dist/assets/services/vendor/squoosh/mozjpeg/mozjpeg_node_enc.js +32 -64
  33. package/dist/assets/services/vendor/squoosh/png/squoosh_png.js +2 -4
  34. package/dist/assets/services/vendor/squoosh/webp/webp_node_dec.js +29 -58
  35. package/dist/assets/services/vendor/squoosh/webp/webp_node_enc.js +29 -58
  36. package/dist/assets/utils/getAssetsPrefix.js +2 -4
  37. package/dist/assets/utils/remotePattern.js +1 -2
  38. package/dist/assets/utils/remoteProbe.js +1 -2
  39. package/dist/assets/utils/vendor/image-size/types/cur.js +1 -2
  40. package/dist/assets/utils/vendor/image-size/types/icns.js +1 -2
  41. package/dist/assets/utils/vendor/image-size/types/ico.js +2 -4
  42. package/dist/assets/utils/vendor/image-size/types/jp2.js +2 -4
  43. package/dist/assets/utils/vendor/image-size/types/utils.js +4 -8
  44. package/dist/assets/vite-plugin-assets.js +1 -1
  45. package/dist/cli/add/babel.d.ts +1 -1
  46. package/dist/cli/add/imports.js +4 -8
  47. package/dist/cli/add/index.js +23 -46
  48. package/dist/cli/add/wrapper.js +1 -2
  49. package/dist/cli/index.js +1 -2
  50. package/dist/cli/info/index.js +1 -2
  51. package/dist/cli/install-package.js +3 -6
  52. package/dist/cli/throw-and-exit.js +1 -2
  53. package/dist/config/index.d.ts +2 -2
  54. package/dist/config/index.js +3 -3
  55. package/dist/content/index.d.ts +1 -2
  56. package/dist/content/index.js +1 -9
  57. package/dist/content/runtime.d.ts +2 -1
  58. package/dist/content/runtime.js +11 -20
  59. package/dist/content/server-listeners.js +5 -10
  60. package/dist/content/types-generator.js +5 -10
  61. package/dist/content/utils.d.ts +0 -4
  62. package/dist/content/utils.js +5 -18
  63. package/dist/content/vite-plugin-content-assets.d.ts +1 -1
  64. package/dist/content/vite-plugin-content-assets.js +14 -47
  65. package/dist/content/vite-plugin-content-imports.js +6 -11
  66. package/dist/content/vite-plugin-content-virtual-mod.js +7 -14
  67. package/dist/core/app/index.js +11 -46
  68. package/dist/core/app/node.js +4 -3
  69. package/dist/core/app/pipeline.d.ts +7 -2
  70. package/dist/core/app/pipeline.js +70 -2
  71. package/dist/core/app/types.d.ts +1 -0
  72. package/dist/core/base-pipeline.d.ts +16 -1
  73. package/dist/core/build/generate.js +16 -62
  74. package/dist/core/build/index.js +3 -5
  75. package/dist/core/build/internal.d.ts +39 -9
  76. package/dist/core/build/internal.js +43 -54
  77. package/dist/core/build/page-data.js +6 -6
  78. package/dist/core/build/pipeline.d.ts +7 -3
  79. package/dist/core/build/pipeline.js +134 -23
  80. package/dist/core/build/plugins/plugin-analyzer.js +11 -32
  81. package/dist/core/build/plugins/plugin-content.d.ts +1 -0
  82. package/dist/core/build/plugins/plugin-content.js +34 -32
  83. package/dist/core/build/plugins/plugin-css.js +23 -51
  84. package/dist/core/build/plugins/plugin-manifest.js +8 -9
  85. package/dist/core/build/plugins/plugin-pages.d.ts +0 -1
  86. package/dist/core/build/plugins/plugin-pages.js +10 -12
  87. package/dist/core/build/plugins/plugin-ssr.js +16 -14
  88. package/dist/core/build/plugins/util.d.ts +26 -11
  89. package/dist/core/build/plugins/util.js +22 -6
  90. package/dist/core/build/static-build.js +31 -26
  91. package/dist/core/build/types.d.ts +6 -6
  92. package/dist/core/client-directive/build.js +1 -2
  93. package/dist/core/compile/compile.js +1 -1
  94. package/dist/core/config/config.js +2 -7
  95. package/dist/core/config/logging.js +1 -2
  96. package/dist/core/config/schema.d.ts +92 -60
  97. package/dist/core/config/schema.js +6 -2
  98. package/dist/core/config/settings.js +1 -2
  99. package/dist/core/config/timer.js +4 -8
  100. package/dist/core/constants.d.ts +1 -1
  101. package/dist/core/constants.js +1 -1
  102. package/dist/core/cookies/cookies.js +3 -6
  103. package/dist/core/dev/container.js +1 -1
  104. package/dist/core/dev/dev.js +1 -1
  105. package/dist/core/dev/restart.js +1 -2
  106. package/dist/core/errors/errors-data.d.ts +25 -1
  107. package/dist/core/errors/errors-data.js +15 -4
  108. package/dist/core/errors/errors.js +1 -2
  109. package/dist/core/errors/index.d.ts +1 -0
  110. package/dist/core/errors/index.js +2 -0
  111. package/dist/core/errors/overlay.js +3 -4
  112. package/dist/core/errors/printer.js +2 -4
  113. package/dist/{content/error-map.js → core/errors/zod-error-map.js} +2 -4
  114. package/dist/core/fs/index.js +2 -4
  115. package/dist/core/logger/vite.js +9 -18
  116. package/dist/core/messages.js +2 -2
  117. package/dist/core/middleware/callMiddleware.d.ts +3 -2
  118. package/dist/core/middleware/callMiddleware.js +13 -3
  119. package/dist/core/middleware/index.js +12 -8
  120. package/dist/core/middleware/sequence.js +22 -4
  121. package/dist/core/module-loader/vite.js +1 -2
  122. package/dist/core/preview/index.js +1 -1
  123. package/dist/core/render/params-and-props.js +2 -4
  124. package/dist/core/render/slots.js +4 -8
  125. package/dist/core/render-context.d.ts +15 -5
  126. package/dist/core/render-context.js +134 -28
  127. package/dist/core/request.js +1 -2
  128. package/dist/core/routing/manifest/create.js +3 -6
  129. package/dist/core/routing/priority.d.ts +1 -1
  130. package/dist/core/sync/index.js +11 -4
  131. package/dist/core/util.d.ts +2 -0
  132. package/dist/core/util.js +18 -19
  133. package/dist/i18n/index.js +2 -4
  134. package/dist/i18n/middleware.js +1 -2
  135. package/dist/i18n/utils.js +1 -2
  136. package/dist/i18n/vite-plugin-i18n.js +1 -2
  137. package/dist/integrations/{index.js → hooks.js} +6 -2
  138. package/dist/jsx/babel.d.ts +3 -0
  139. package/dist/jsx/babel.js +9 -18
  140. package/dist/jsx/rehype.d.ts +11 -0
  141. package/dist/jsx/rehype.js +197 -0
  142. package/dist/jsx/server.js +20 -14
  143. package/dist/jsx/transform-options.d.ts +3 -0
  144. package/dist/jsx-runtime/index.js +8 -16
  145. package/dist/preferences/index.js +3 -6
  146. package/dist/preferences/store.js +3 -6
  147. package/dist/prefetch/index.js +8 -16
  148. package/dist/prefetch/vite-plugin-prefetch.js +2 -4
  149. package/dist/prerender/metadata.js +1 -2
  150. package/dist/prerender/routing.js +1 -1
  151. package/dist/prerender/utils.d.ts +1 -2
  152. package/dist/prerender/utils.js +2 -5
  153. package/dist/runtime/client/dev-toolbar/apps/astro.js +5 -10
  154. package/dist/runtime/client/dev-toolbar/apps/audit/index.js +5 -10
  155. package/dist/runtime/client/dev-toolbar/apps/audit/rules/a11y.js +45 -90
  156. package/dist/runtime/client/dev-toolbar/apps/audit/rules/index.js +1 -2
  157. package/dist/runtime/client/dev-toolbar/apps/audit/rules/perf.js +16 -32
  158. package/dist/runtime/client/dev-toolbar/apps/audit/ui/audit-list-window.js +2 -4
  159. package/dist/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.js +3 -6
  160. package/dist/runtime/client/dev-toolbar/apps/utils/highlight.js +1 -2
  161. package/dist/runtime/client/dev-toolbar/apps/utils/window.js +4 -8
  162. package/dist/runtime/client/dev-toolbar/entrypoint.js +8 -11
  163. package/dist/runtime/client/dev-toolbar/helpers.d.ts +1 -1
  164. package/dist/runtime/client/dev-toolbar/helpers.js +3 -5
  165. package/dist/runtime/client/dev-toolbar/toolbar.js +11 -22
  166. package/dist/runtime/client/dev-toolbar/ui-library/badge.js +1 -2
  167. package/dist/runtime/client/dev-toolbar/ui-library/button.d.ts +5 -0
  168. package/dist/runtime/client/dev-toolbar/ui-library/button.js +26 -5
  169. package/dist/runtime/client/dev-toolbar/ui-library/index.d.ts +1 -0
  170. package/dist/runtime/client/dev-toolbar/ui-library/index.js +2 -0
  171. package/dist/runtime/client/dev-toolbar/ui-library/radio-checkbox.d.ts +13 -0
  172. package/dist/runtime/client/dev-toolbar/ui-library/radio-checkbox.js +109 -0
  173. package/dist/runtime/client/visible.js +1 -2
  174. package/dist/runtime/server/astro-component.js +2 -4
  175. package/dist/runtime/server/astro-global.js +1 -1
  176. package/dist/runtime/server/astro-island.js +7 -14
  177. package/dist/runtime/server/astro-island.prebuilt-dev.d.ts +1 -1
  178. package/dist/runtime/server/astro-island.prebuilt-dev.js +1 -1
  179. package/dist/runtime/server/astro-island.prebuilt.d.ts +1 -1
  180. package/dist/runtime/server/astro-island.prebuilt.js +1 -1
  181. package/dist/runtime/server/index.js +3 -6
  182. package/dist/runtime/server/jsx.js +1 -2
  183. package/dist/runtime/server/render/any.js +1 -2
  184. package/dist/runtime/server/render/astro/instance.js +11 -12
  185. package/dist/runtime/server/render/astro/render.js +5 -10
  186. package/dist/runtime/server/render/component.js +6 -11
  187. package/dist/runtime/server/render/dom.js +1 -2
  188. package/dist/runtime/server/render/page.js +1 -2
  189. package/dist/runtime/server/render/script.js +1 -2
  190. package/dist/runtime/server/render/slot.js +1 -2
  191. package/dist/runtime/server/render/tags.js +2 -4
  192. package/dist/runtime/server/render/util.js +5 -5
  193. package/dist/runtime/server/shorthash.js +1 -2
  194. package/dist/runtime/server/transition.js +4 -8
  195. package/dist/runtime/server/util.js +1 -2
  196. package/dist/transitions/events.d.ts +6 -5
  197. package/dist/transitions/events.js +17 -10
  198. package/dist/transitions/router.js +100 -132
  199. package/dist/transitions/swap-functions.d.ts +12 -0
  200. package/dist/transitions/swap-functions.js +105 -0
  201. package/dist/vite-plugin-astro/compile.js +1 -2
  202. package/dist/vite-plugin-astro/hmr.js +5 -10
  203. package/dist/vite-plugin-astro/index.js +2 -4
  204. package/dist/vite-plugin-astro-server/pipeline.d.ts +8 -3
  205. package/dist/vite-plugin-astro-server/pipeline.js +59 -11
  206. package/dist/vite-plugin-astro-server/plugin.js +6 -6
  207. package/dist/vite-plugin-astro-server/response.js +1 -2
  208. package/dist/vite-plugin-astro-server/route.js +36 -42
  209. package/dist/vite-plugin-astro-server/vite.js +5 -7
  210. package/dist/vite-plugin-config-alias/index.js +7 -14
  211. package/dist/vite-plugin-head/index.js +3 -6
  212. package/dist/vite-plugin-html/index.js +1 -2
  213. package/dist/vite-plugin-html/transform/escape.js +2 -4
  214. package/dist/vite-plugin-html/transform/slots.js +1 -2
  215. package/dist/vite-plugin-html/transform/utils.js +1 -2
  216. package/dist/vite-plugin-inject-env-ts/index.js +37 -11
  217. package/dist/vite-plugin-integrations-container/index.js +4 -7
  218. package/dist/vite-plugin-load-fallback/index.js +1 -2
  219. package/dist/vite-plugin-markdown/index.js +1 -2
  220. package/dist/vite-plugin-mdx/index.d.ts +3 -0
  221. package/dist/vite-plugin-mdx/tag.d.ts +2 -0
  222. package/dist/vite-plugin-mdx/tag.js +3 -6
  223. package/dist/vite-plugin-mdx/transform-jsx.d.ts +3 -0
  224. package/dist/vite-plugin-mdx/transform-jsx.js +1 -2
  225. package/dist/vite-plugin-scanner/index.js +4 -6
  226. package/dist/vite-plugin-scanner/scan.js +2 -4
  227. package/dist/vite-plugin-scripts/page-ssr.js +3 -6
  228. package/package.json +26 -22
  229. package/templates/actions.mjs +61 -0
  230. package/types/actions.d.ts +3 -0
  231. package/types/content.d.ts +2 -2
  232. /package/dist/{content/error-map.d.ts → core/errors/zod-error-map.d.ts} +0 -0
  233. /package/dist/integrations/{astroFeaturesValidation.d.ts → features-validation.d.ts} +0 -0
  234. /package/dist/integrations/{astroFeaturesValidation.js → features-validation.js} +0 -0
  235. /package/dist/integrations/{index.d.ts → hooks.d.ts} +0 -0
@@ -0,0 +1,105 @@
1
+ const PERSIST_ATTR = "data-astro-transition-persist";
2
+ function deselectScripts(doc) {
3
+ for (const s1 of document.scripts) {
4
+ for (const s2 of doc.scripts) {
5
+ if (
6
+ // Check if the script should be rerun regardless of it being the same
7
+ !s2.hasAttribute("data-astro-rerun") && // Inline
8
+ (!s1.src && s1.textContent === s2.textContent || // External
9
+ s1.src && s1.type === s2.type && s1.src === s2.src)
10
+ ) {
11
+ s2.dataset.astroExec = "";
12
+ break;
13
+ }
14
+ }
15
+ }
16
+ }
17
+ function swapRootAttributes(doc) {
18
+ const html = document.documentElement;
19
+ const astroAttributes = [...html.attributes].filter(
20
+ ({ name }) => (html.removeAttribute(name), name.startsWith("data-astro-"))
21
+ );
22
+ [...doc.documentElement.attributes, ...astroAttributes].forEach(
23
+ ({ name, value }) => html.setAttribute(name, value)
24
+ );
25
+ }
26
+ function swapHeadElements(doc) {
27
+ for (const el of Array.from(document.head.children)) {
28
+ const newEl = persistedHeadElement(el, doc);
29
+ if (newEl) {
30
+ newEl.remove();
31
+ } else {
32
+ el.remove();
33
+ }
34
+ }
35
+ document.head.append(...doc.head.children);
36
+ }
37
+ function swapBodyElement(newElement, oldElement) {
38
+ oldElement.replaceWith(newElement);
39
+ for (const el of oldElement.querySelectorAll(`[${PERSIST_ATTR}]`)) {
40
+ const id = el.getAttribute(PERSIST_ATTR);
41
+ const newEl = newElement.querySelector(`[${PERSIST_ATTR}="${id}"]`);
42
+ if (newEl) {
43
+ newEl.replaceWith(el);
44
+ if (newEl.localName === "astro-island" && shouldCopyProps(el)) {
45
+ el.setAttribute("ssr", "");
46
+ el.setAttribute("props", newEl.getAttribute("props"));
47
+ }
48
+ }
49
+ }
50
+ }
51
+ const saveFocus = () => {
52
+ const activeElement = document.activeElement;
53
+ if (activeElement?.closest(`[${PERSIST_ATTR}]`)) {
54
+ if (activeElement instanceof HTMLInputElement || activeElement instanceof HTMLTextAreaElement) {
55
+ const start = activeElement.selectionStart;
56
+ const end = activeElement.selectionEnd;
57
+ return () => restoreFocus({ activeElement, start, end });
58
+ }
59
+ return () => restoreFocus({ activeElement });
60
+ } else {
61
+ return () => restoreFocus({ activeElement: null });
62
+ }
63
+ };
64
+ const restoreFocus = ({ activeElement, start, end }) => {
65
+ if (activeElement) {
66
+ activeElement.focus();
67
+ if (activeElement instanceof HTMLInputElement || activeElement instanceof HTMLTextAreaElement) {
68
+ if (typeof start === "number") activeElement.selectionStart = start;
69
+ if (typeof end === "number") activeElement.selectionEnd = end;
70
+ }
71
+ }
72
+ };
73
+ const persistedHeadElement = (el, newDoc) => {
74
+ const id = el.getAttribute(PERSIST_ATTR);
75
+ const newEl = id && newDoc.head.querySelector(`[${PERSIST_ATTR}="${id}"]`);
76
+ if (newEl) {
77
+ return newEl;
78
+ }
79
+ if (el.matches("link[rel=stylesheet]")) {
80
+ const href = el.getAttribute("href");
81
+ return newDoc.head.querySelector(`link[rel=stylesheet][href="${href}"]`);
82
+ }
83
+ return null;
84
+ };
85
+ const shouldCopyProps = (el) => {
86
+ const persistProps = el.dataset.astroTransitionPersistProps;
87
+ return persistProps == null || persistProps === "false";
88
+ };
89
+ const swap = (doc) => {
90
+ deselectScripts(doc);
91
+ swapRootAttributes(doc);
92
+ swapHeadElements(doc);
93
+ const restoreFocusFunction = saveFocus();
94
+ swapBodyElement(doc.body, document.body);
95
+ restoreFocusFunction();
96
+ };
97
+ export {
98
+ deselectScripts,
99
+ restoreFocus,
100
+ saveFocus,
101
+ swap,
102
+ swapBodyElement,
103
+ swapHeadElements,
104
+ swapRootAttributes
105
+ };
@@ -71,8 +71,7 @@ async function enhanceCompileError({
71
71
  const scannedFrontmatter = frontmatterRE.exec(source);
72
72
  if (scannedFrontmatter) {
73
73
  const frontmatter = scannedFrontmatter[1].replace(/\breturn\b/g, "throw");
74
- if (lineText && !frontmatter.includes(lineText))
75
- throw err;
74
+ if (lineText && !frontmatter.includes(lineText)) throw err;
76
75
  try {
77
76
  await transformWithEsbuild(frontmatter, id, {
78
77
  loader: "ts",
@@ -7,8 +7,7 @@ async function handleHotUpdate(ctx, { logger, astroFileToCompileMetadata }) {
7
7
  }
8
8
  }
9
9
  const oldCode = astroFileToCompileMetadata.get(ctx.file)?.originalCode;
10
- if (oldCode == null)
11
- return;
10
+ if (oldCode == null) return;
12
11
  const newCode = await ctx.read();
13
12
  if (isStyleOnlyChanged(oldCode, newCode)) {
14
13
  logger.debug("watch", "style-only change");
@@ -19,26 +18,22 @@ async function handleHotUpdate(ctx, { logger, astroFileToCompileMetadata }) {
19
18
  const scriptRE = /<script(?:\s.*?)?>.*?<\/script>/gs;
20
19
  const styleRE = /<style(?:\s.*?)?>.*?<\/style>/gs;
21
20
  function isStyleOnlyChanged(oldCode, newCode) {
22
- if (oldCode === newCode)
23
- return false;
21
+ if (oldCode === newCode) return false;
24
22
  let oldFrontmatter = "";
25
23
  let newFrontmatter = "";
26
24
  oldCode = oldCode.replace(frontmatterRE, (m) => (oldFrontmatter = m, ""));
27
25
  newCode = newCode.replace(frontmatterRE, (m) => (newFrontmatter = m, ""));
28
- if (oldFrontmatter !== newFrontmatter)
29
- return false;
26
+ if (oldFrontmatter !== newFrontmatter) return false;
30
27
  const oldScripts = [];
31
28
  const newScripts = [];
32
29
  oldCode = oldCode.replace(scriptRE, (m) => (oldScripts.push(m), ""));
33
30
  newCode = newCode.replace(scriptRE, (m) => (newScripts.push(m), ""));
34
- if (!isArrayEqual(oldScripts, newScripts))
35
- return false;
31
+ if (!isArrayEqual(oldScripts, newScripts)) return false;
36
32
  const oldStyles = [];
37
33
  const newStyles = [];
38
34
  oldCode = oldCode.replace(styleRE, (m) => (oldStyles.push(m), ""));
39
35
  newCode = newCode.replace(styleRE, (m) => (newStyles.push(m), ""));
40
- if (oldCode !== newCode)
41
- return false;
36
+ if (oldCode !== newCode) return false;
42
37
  return oldStyles.length === newStyles.length && !isArrayEqual(oldStyles, newStyles);
43
38
  }
44
39
  function isArrayEqual(a, b) {
@@ -57,8 +57,7 @@ function astro({ settings, logger }) {
57
57
  if (!compileMetadata) {
58
58
  if (server) {
59
59
  const code = await loadId(server.pluginContainer, filename);
60
- if (code != null)
61
- await compile(code, filename);
60
+ if (code != null) await compile(code, filename);
62
61
  } else if (config.experimental.contentCollectionCache) {
63
62
  await this.load({
64
63
  id: filename,
@@ -191,8 +190,7 @@ File: ${id}`
191
190
  return [prePlugin, normalPlugin];
192
191
  }
193
192
  function appendSourceMap(content, map) {
194
- if (!map)
195
- return content;
193
+ if (!map) return content;
196
194
  return `${content}
197
195
  //# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(
198
196
  map
@@ -1,4 +1,4 @@
1
- import type { AstroSettings, ComponentInstance, RouteData, SSRLoadedRenderer, SSRManifest } from '../@types/astro.js';
1
+ import type { AstroSettings, ComponentInstance, ManifestData, RewritePayload, RouteData, SSRLoadedRenderer, SSRManifest } from '../@types/astro.js';
2
2
  import type { HeadElements } from '../core/base-pipeline.js';
3
3
  import type { Logger } from '../core/logger/core.js';
4
4
  import type { ModuleLoader } from '../core/module-loader/index.js';
@@ -10,10 +10,15 @@ export declare class DevPipeline extends Pipeline {
10
10
  readonly settings: AstroSettings;
11
11
  readonly config: import("../@types/astro.js").AstroConfig;
12
12
  renderers: SSRLoadedRenderer[];
13
+ manifestData: ManifestData | undefined;
14
+ componentInterner: WeakMap<RouteData, ComponentInstance>;
13
15
  private constructor();
14
- static create({ loader, logger, manifest, settings, }: Pick<DevPipeline, 'loader' | 'logger' | 'manifest' | 'settings'>): DevPipeline;
16
+ static create(manifestData: ManifestData, { loader, logger, manifest, settings, }: Pick<DevPipeline, 'loader' | 'logger' | 'manifest' | 'settings'>): DevPipeline;
15
17
  headElements(routeData: RouteData): Promise<HeadElements>;
16
18
  componentMetadata(routeData: RouteData): Promise<Map<string, import("../@types/astro.js").SSRComponentMetadata>>;
17
- preload(filePath: URL): Promise<ComponentInstance>;
19
+ preload(routeData: RouteData, filePath: URL): Promise<ComponentInstance>;
18
20
  clearRouteCache(): void;
21
+ getComponentByRoute(routeData: RouteData): Promise<ComponentInstance>;
22
+ tryRewrite(payload: RewritePayload): Promise<[RouteData, ComponentInstance]>;
23
+ setManifestData(manifestData: ManifestData): void;
19
24
  }
@@ -1,11 +1,11 @@
1
- import url from "node:url";
1
+ import { fileURLToPath } from "node:url";
2
2
  import { getInfoOutput } from "../cli/info/index.js";
3
3
  import { ASTRO_VERSION, DEFAULT_404_COMPONENT } from "../core/constants.js";
4
4
  import { enhanceViteSSRError } from "../core/errors/dev/index.js";
5
- import { AggregateError, CSSError, MarkdownError } from "../core/errors/index.js";
5
+ import { RouteNotFound } from "../core/errors/errors-data.js";
6
+ import { AggregateError, AstroError, CSSError, MarkdownError } from "../core/errors/index.js";
6
7
  import { Pipeline, loadRenderer } from "../core/render/index.js";
7
- import { isPage, resolveIdToUrl, viteID } from "../core/util.js";
8
- import { isServerLikeOutput } from "../prerender/utils.js";
8
+ import { isPage, isServerLikeOutput, resolveIdToUrl, viteID } from "../core/util.js";
9
9
  import { PAGE_SCRIPT_ID } from "../vite-plugin-scripts/index.js";
10
10
  import { getStylesForURL } from "./css.js";
11
11
  import { getComponentMetadata } from "./metadata.js";
@@ -28,13 +28,17 @@ class DevPipeline extends Pipeline {
28
28
  // renderers are loaded on every request,
29
29
  // so it needs to be mutable here unlike in other environments
30
30
  renderers = new Array();
31
- static create({
31
+ manifestData;
32
+ componentInterner = /* @__PURE__ */ new WeakMap();
33
+ static create(manifestData, {
32
34
  loader,
33
35
  logger,
34
36
  manifest,
35
37
  settings
36
38
  }) {
37
- return new DevPipeline(loader, logger, manifest, settings);
39
+ const pipeline = new DevPipeline(loader, logger, manifest, settings);
40
+ pipeline.manifestData = manifestData;
41
+ return pipeline;
38
42
  }
39
43
  async headElements(routeData) {
40
44
  const {
@@ -43,7 +47,7 @@ class DevPipeline extends Pipeline {
43
47
  mode,
44
48
  settings
45
49
  } = this;
46
- const filePath = new URL(`./${routeData.component}`, root);
50
+ const filePath = new URL(`${routeData.component}`, root);
47
51
  const { scripts } = settings.config.experimental.directRenderScript ? { scripts: /* @__PURE__ */ new Set() } : await getScriptsForURL(filePath, settings.config.root, loader);
48
52
  if (isPage(filePath, settings) && mode === "development") {
49
53
  scripts.add({
@@ -54,7 +58,7 @@ class DevPipeline extends Pipeline {
54
58
  const src = await resolveIdToUrl(loader, "astro/runtime/client/dev-toolbar/entrypoint.js");
55
59
  scripts.add({ props: { type: "module", src }, children: "" });
56
60
  const additionalMetadata = {
57
- root: url.fileURLToPath(settings.config.root),
61
+ root: fileURLToPath(settings.config.root),
58
62
  version: ASTRO_VERSION,
59
63
  latestAstroVersion: settings.latestAstroVersion,
60
64
  debugInfo: await getInfoOutput({ userConfig: settings.config, print: false })
@@ -93,10 +97,10 @@ class DevPipeline extends Pipeline {
93
97
  config: { root },
94
98
  loader
95
99
  } = this;
96
- const filePath = new URL(`./${routeData.component}`, root);
100
+ const filePath = new URL(`${routeData.component}`, root);
97
101
  return getComponentMetadata(filePath, loader);
98
102
  }
99
- async preload(filePath) {
103
+ async preload(routeData, filePath) {
100
104
  const { loader } = this;
101
105
  if (filePath.href === new URL(DEFAULT_404_COMPONENT, this.config.root).href) {
102
106
  return { default: default404Page };
@@ -105,7 +109,9 @@ class DevPipeline extends Pipeline {
105
109
  const renderers_ = await Promise.all(renderers__);
106
110
  this.renderers = renderers_.filter((r) => Boolean(r));
107
111
  try {
108
- return await loader.import(viteID(filePath));
112
+ const componentInstance = await loader.import(viteID(filePath));
113
+ this.componentInterner.set(routeData, componentInstance);
114
+ return componentInstance;
109
115
  } catch (error) {
110
116
  if (MarkdownError.is(error) || CSSError.is(error) || AggregateError.is(error)) {
111
117
  throw error;
@@ -115,6 +121,48 @@ class DevPipeline extends Pipeline {
115
121
  }
116
122
  clearRouteCache() {
117
123
  this.routeCache.clearAll();
124
+ this.componentInterner = /* @__PURE__ */ new WeakMap();
125
+ }
126
+ async getComponentByRoute(routeData) {
127
+ const component = this.componentInterner.get(routeData);
128
+ if (component) {
129
+ return component;
130
+ } else {
131
+ const filePath = new URL(`${routeData.component}`, this.config.root);
132
+ return await this.preload(routeData, filePath);
133
+ }
134
+ }
135
+ async tryRewrite(payload) {
136
+ let foundRoute;
137
+ if (!this.manifestData) {
138
+ throw new Error("Missing manifest data. This is an internal error, please file an issue.");
139
+ }
140
+ for (const route of this.manifestData.routes) {
141
+ if (payload instanceof URL) {
142
+ if (route.pattern.test(payload.pathname)) {
143
+ foundRoute = route;
144
+ break;
145
+ }
146
+ } else if (payload instanceof Request) {
147
+ const url = new URL(payload.url);
148
+ if (route.pattern.test(url.pathname)) {
149
+ foundRoute = route;
150
+ break;
151
+ }
152
+ } else if (route.pattern.test(decodeURI(payload))) {
153
+ foundRoute = route;
154
+ break;
155
+ }
156
+ }
157
+ if (foundRoute) {
158
+ const componentInstance = await this.getComponentByRoute(foundRoute);
159
+ return [foundRoute, componentInstance];
160
+ } else {
161
+ throw new AstroError(RouteNotFound);
162
+ }
163
+ }
164
+ setManifestData(manifestData) {
165
+ this.manifestData = manifestData;
118
166
  }
119
167
  }
120
168
  export {
@@ -23,16 +23,17 @@ function createVitePluginAstroServer({
23
23
  configureServer(viteServer) {
24
24
  const loader = createViteLoader(viteServer);
25
25
  const manifest = createDevelopmentManifest(settings);
26
- const pipeline = DevPipeline.create({ loader, logger, manifest, settings });
27
26
  let manifestData = ensure404Route(
28
27
  createRouteManifest({ settings, fsMod }, logger)
29
28
  );
29
+ const pipeline = DevPipeline.create(manifestData, { loader, logger, manifest, settings });
30
30
  const controller = createController({ loader });
31
31
  const localStorage = new AsyncLocalStorage();
32
32
  function rebuildManifest(needsManifestRebuild) {
33
33
  pipeline.clearRouteCache();
34
34
  if (needsManifestRebuild) {
35
35
  manifestData = ensure404Route(createRouteManifest({ settings }, logger));
36
+ pipeline.setManifestData(manifestData);
36
37
  }
37
38
  }
38
39
  viteServer.watcher.on("add", rebuildManifest.bind(null, true));
@@ -79,10 +80,8 @@ function createVitePluginAstroServer({
79
80
  };
80
81
  },
81
82
  transform(code, id, opts = {}) {
82
- if (opts.ssr)
83
- return;
84
- if (!id.includes("vite/dist/client/client.mjs"))
85
- return;
83
+ if (opts.ssr) return;
84
+ if (!id.includes("vite/dist/client/client.mjs")) return;
86
85
  return patchOverlay(code);
87
86
  }
88
87
  };
@@ -105,7 +104,7 @@ function createDevelopmentManifest(settings) {
105
104
  assets: /* @__PURE__ */ new Set(),
106
105
  entryModules: {},
107
106
  routes: [],
108
- adapterName: "",
107
+ adapterName: settings?.adapter?.name || "",
109
108
  clientDirectives: settings.clientDirectives,
110
109
  renderers: [],
111
110
  base: settings.config.base,
@@ -115,6 +114,7 @@ function createDevelopmentManifest(settings) {
115
114
  inlinedScripts: /* @__PURE__ */ new Map(),
116
115
  i18n: i18nManifest,
117
116
  checkOrigin: settings.config.experimental.security?.csrfProtection?.origin ?? false,
117
+ rewritingEnabled: settings.config.experimental.rewriting,
118
118
  middleware(_, next) {
119
119
  return next();
120
120
  }
@@ -78,8 +78,7 @@ async function writeWebResponse(res, webResponse) {
78
78
  });
79
79
  while (true) {
80
80
  const { done, value } = await reader.read();
81
- if (done)
82
- break;
81
+ if (done) break;
83
82
  if (value) {
84
83
  res.write(value);
85
84
  }
@@ -78,7 +78,7 @@ ${AstroErrorData.NoMatchingStaticPathFound.hint(possibleRoutes)}`
78
78
  }
79
79
  if (custom404) {
80
80
  const filePath = new URL(`./${custom404.component}`, config.root);
81
- const preloadedComponent = await pipeline.preload(filePath);
81
+ const preloadedComponent = await pipeline.preload(custom404, filePath);
82
82
  return {
83
83
  route: custom404,
84
84
  filePath,
@@ -139,40 +139,38 @@ async function handleRoute({
139
139
  if (!pathNameHasLocale && pathname !== "/") {
140
140
  return handle404Response(origin, incomingRequest, incomingResponse);
141
141
  }
142
- request = createRequest({
143
- base: config.base,
144
- url,
145
- headers: incomingRequest.headers,
146
- logger,
147
- // no route found, so we assume the default for rendering the 404 page
148
- staticLike: config.output === "static" || config.output === "hybrid"
149
- });
150
- route = {
151
- component: "",
152
- generate(_data) {
153
- return "";
154
- },
155
- params: [],
156
- // Disable eslint as we only want to generate an empty RegExp
157
- // eslint-disable-next-line prefer-regex-literals
158
- pattern: new RegExp(""),
159
- prerender: false,
160
- segments: [],
161
- type: "fallback",
162
- route: "",
163
- fallbackRoutes: [],
164
- isIndex: false
165
- };
166
- renderContext = RenderContext.create({
167
- pipeline,
168
- pathname,
169
- middleware,
170
- request,
171
- routeData: route
172
- });
173
- } else {
174
- return handle404Response(origin, incomingRequest, incomingResponse);
175
142
  }
143
+ request = createRequest({
144
+ base: config.base,
145
+ url,
146
+ headers: incomingRequest.headers,
147
+ logger,
148
+ // no route found, so we assume the default for rendering the 404 page
149
+ staticLike: config.output === "static" || config.output === "hybrid"
150
+ });
151
+ route = {
152
+ component: "",
153
+ generate(_data) {
154
+ return "";
155
+ },
156
+ params: [],
157
+ // Disable eslint as we only want to generate an empty RegExp
158
+ // eslint-disable-next-line prefer-regex-literals
159
+ pattern: new RegExp(""),
160
+ prerender: false,
161
+ segments: [],
162
+ type: "fallback",
163
+ route: "",
164
+ fallbackRoutes: [],
165
+ isIndex: false
166
+ };
167
+ renderContext = RenderContext.create({
168
+ pipeline,
169
+ pathname,
170
+ middleware,
171
+ request,
172
+ routeData: route
173
+ });
176
174
  } else {
177
175
  const filePath = matchedRoute.filePath;
178
176
  const { preloadedComponent } = matchedRoute;
@@ -188,8 +186,7 @@ async function handleRoute({
188
186
  staticLike: config.output === "static" || route.prerender
189
187
  });
190
188
  for (const [name, value] of Object.entries(config.server.headers ?? {})) {
191
- if (value)
192
- incomingResponse.setHeader(name, value);
189
+ if (value) incomingResponse.setHeader(name, value);
193
190
  }
194
191
  options = {
195
192
  pipeline,
@@ -258,12 +255,9 @@ async function handleRoute({
258
255
  await writeSSRResult(request, response, incomingResponse);
259
256
  }
260
257
  function getStatus(matchedRoute) {
261
- if (!matchedRoute)
262
- return 404;
263
- if (matchedRoute.route.route === "/404")
264
- return 404;
265
- if (matchedRoute.route.route === "/500")
266
- return 500;
258
+ if (!matchedRoute) return 404;
259
+ if (matchedRoute.route.route === "/404") return 404;
260
+ if (matchedRoute.route.route === "/500") return 500;
267
261
  }
268
262
  export {
269
263
  handleRoute,
@@ -15,7 +15,7 @@ async function* crawlGraph(loader, _id, isRootFile, scanned = /* @__PURE__ */ ne
15
15
  loader.getModulesByFile(id) ?? /* @__PURE__ */ new Set()
16
16
  ) : (
17
17
  // For non-root files, we're safe to pull from "getModuleById" based on testing.
18
- // TODO: Find better invalidation strat to use "getModuleById" in all cases!
18
+ // TODO: Find better invalidation strategy to use "getModuleById" in all cases!
19
19
  /* @__PURE__ */ new Set([loader.getModuleById(id)])
20
20
  );
21
21
  for (const entry of moduleEntriesForId) {
@@ -24,14 +24,12 @@ async function* crawlGraph(loader, _id, isRootFile, scanned = /* @__PURE__ */ ne
24
24
  }
25
25
  if (id === entry.id) {
26
26
  scanned.add(id);
27
- const entryIsStyle = isCSSRequest(id);
27
+ if (isCSSRequest(id)) {
28
+ continue;
29
+ }
28
30
  for (const importedModule of entry.importedModules) {
29
- if (!importedModule.id)
30
- continue;
31
+ if (!importedModule.id) continue;
31
32
  const importedModulePathname = importedModule.id.replace(STRIP_QUERY_PARAMS_REGEX, "");
32
- if (entryIsStyle && !isCSSRequest(importedModulePathname)) {
33
- continue;
34
- }
35
33
  const isFileTypeNeedingSSR = fileExtensionsToSSR.has(npath.extname(importedModulePathname));
36
34
  const isPropagationStoppingPoint = ASTRO_PROPAGATED_ASSET_REGEX.test(importedModule.id);
37
35
  if (isFileTypeNeedingSSR && // Should not SSR a module with ?astroPropagatedAssets
@@ -2,11 +2,9 @@ import path from "node:path";
2
2
  import { normalizePath } from "vite";
3
3
  const getConfigAlias = (settings) => {
4
4
  const { tsConfig, tsConfigPath } = settings;
5
- if (!tsConfig || !tsConfigPath || !tsConfig.compilerOptions)
6
- return null;
5
+ if (!tsConfig || !tsConfigPath || !tsConfig.compilerOptions) return null;
7
6
  const { baseUrl, paths } = tsConfig.compilerOptions;
8
- if (!baseUrl)
9
- return null;
7
+ if (!baseUrl) return null;
10
8
  const resolvedBaseUrl = path.resolve(path.dirname(tsConfigPath), baseUrl);
11
9
  const aliases = [];
12
10
  if (paths) {
@@ -33,8 +31,7 @@ function configAliasVitePlugin({
33
31
  settings
34
32
  }) {
35
33
  const configAlias = getConfigAlias(settings);
36
- if (!configAlias)
37
- return null;
34
+ if (!configAlias) return null;
38
35
  const plugin = {
39
36
  name: "astro:tsconfig-alias",
40
37
  // use post to only resolve ids that all other plugins before it can't
@@ -43,8 +40,7 @@ function configAliasVitePlugin({
43
40
  patchCreateResolver(config, plugin);
44
41
  },
45
42
  async resolveId(id, importer, options) {
46
- if (isVirtualId(id))
47
- return;
43
+ if (isVirtualId(id)) return;
48
44
  for (const alias of configAlias) {
49
45
  if (alias.find.test(id)) {
50
46
  const updatedId = id.replace(alias.find, alias.replacement);
@@ -52,8 +48,7 @@ function configAliasVitePlugin({
52
48
  return updatedId;
53
49
  }
54
50
  const resolved = await this.resolve(updatedId, importer, { skipSelf: true, ...options });
55
- if (resolved)
56
- return resolved;
51
+ if (resolved) return resolved;
57
52
  }
58
53
  }
59
54
  }
@@ -80,15 +75,13 @@ function patchCreateResolver(config, postPlugin) {
80
75
  ssr
81
76
  };
82
77
  const result = await resolver.apply(_createResolver, args2);
83
- if (result)
84
- return result;
78
+ if (result) return result;
85
79
  const resolved = await postPlugin.resolveId.apply(fakePluginContext, [
86
80
  id,
87
81
  importer,
88
82
  fakeResolveIdOpts
89
83
  ]);
90
- if (resolved)
91
- return resolved;
84
+ if (resolved) return resolved;
92
85
  };
93
86
  };
94
87
  }
@@ -4,8 +4,7 @@ const injectExp = /(?:^\/\/|\/\/!)\s*astro-head-inject/;
4
4
  function configHeadVitePlugin() {
5
5
  let server;
6
6
  function propagateMetadata(id, prop, value, seen = /* @__PURE__ */ new Set()) {
7
- if (seen.has(id))
8
- return;
7
+ if (seen.has(id)) return;
9
8
  seen.add(id);
10
9
  const mod = server.moduleGraph.getModuleById(id);
11
10
  const info = this.getModuleInfo(id);
@@ -80,8 +79,7 @@ function astroHeadBuildPlugin(internals) {
80
79
  generateBundle(_opts, bundle) {
81
80
  const map = internals.componentMetadata;
82
81
  function getOrCreateMetadata(id) {
83
- if (map.has(id))
84
- return map.get(id);
82
+ if (map.has(id)) return map.get(id);
85
83
  const metadata = {
86
84
  propagation: "none",
87
85
  containsHead: false
@@ -90,8 +88,7 @@ function astroHeadBuildPlugin(internals) {
90
88
  return metadata;
91
89
  }
92
90
  for (const [, output] of Object.entries(bundle)) {
93
- if (output.type !== "chunk")
94
- continue;
91
+ if (output.type !== "chunk") continue;
95
92
  for (const [id, mod] of Object.entries(output.modules)) {
96
93
  const modinfo = this.getModuleInfo(id);
97
94
  if (modinfo) {
@@ -6,8 +6,7 @@ function html() {
6
6
  options.plugins = options.plugins?.filter((p) => p.name !== "vite:build-html");
7
7
  },
8
8
  async transform(source, id) {
9
- if (!id.endsWith(".html"))
10
- return;
9
+ if (!id.endsWith(".html")) return;
11
10
  return await transform(source, id);
12
11
  }
13
12
  };
@@ -12,14 +12,12 @@ const rehypeEscape = ({ s }) => {
12
12
  );
13
13
  }
14
14
  } else if (node.type === "element") {
15
- if (!node.properties)
16
- return;
15
+ if (!node.properties) return;
17
16
  for (let [key, value] of Object.entries(node.properties)) {
18
17
  key = key.replace(/([A-Z])/g, "-$1").toLowerCase();
19
18
  const newKey = needsEscape(key) ? escapeTemplateLiteralCharacters(key) : key;
20
19
  const newValue = needsEscape(value) ? escapeTemplateLiteralCharacters(value) : value;
21
- if (newKey === key && newValue === value)
22
- continue;
20
+ if (newKey === key && newValue === value) continue;
23
21
  replaceAttribute(s, node, key, value === "" ? newKey : `${newKey}="${newValue}"`);
24
22
  }
25
23
  }
@@ -4,8 +4,7 @@ const rehypeSlots = ({ s }) => {
4
4
  return (tree, file) => {
5
5
  visit(tree, (node) => {
6
6
  if (node.type === "element" && node.tagName === "slot") {
7
- if (typeof node.properties?.["is:inline"] !== "undefined")
8
- return;
7
+ if (typeof node.properties?.["is:inline"] !== "undefined") return;
9
8
  const name = node.properties?.["name"] ?? "default";
10
9
  const start = node.position?.start.offset ?? 0;
11
10
  const end = node.position?.end.offset ?? 0;
@@ -3,8 +3,7 @@ function replaceAttribute(s, node, key, newValue) {
3
3
  splitAttrsTokenizer.lastIndex = 0;
4
4
  const text = s.original.slice(node.position?.start.offset ?? 0, node.position?.end.offset ?? 0).toString();
5
5
  const offset = text.indexOf(key);
6
- if (offset === -1)
7
- return;
6
+ if (offset === -1) return;
8
7
  const start = node.position.start.offset + offset;
9
8
  const tokens = text.slice(offset).split(splitAttrsTokenizer);
10
9
  const token = tokens[0].replace(/([^>])>[\s\S]*$/gm, "$1");