@patternfly/patternfly-doc-core 1.10.0 → 1.11.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 (117) hide show
  1. package/astro.config.mjs +3 -4
  2. package/cli/cli.ts +60 -19
  3. package/dist/.assetsignore +2 -0
  4. package/dist/{client/_astro/Button.BQCwQ5pE.js → _astro/Button.BVfR1y85.js} +1 -1
  5. package/dist/_astro/CSSTable.E6iSHjec.js +1 -0
  6. package/dist/_astro/ClientRouter.astro_astro_type_script_index_0_lang.CtSceO8m.js +1 -0
  7. package/dist/{client/_astro/Content.B4M2qzJY.js → _astro/Content.CYLxURqU.js} +1 -1
  8. package/dist/{client/_astro/DropdownList.cxp03sS4.js → _astro/DropdownList.-xE7qrND.js} +1 -1
  9. package/dist/{client/_astro/LiveExample.DjPiO80i.js → _astro/LiveExample.CVVccYEB.js} +3 -3
  10. package/dist/{client/_astro/Navigation.kbLxctIo.js → _astro/Navigation.CONcolRR.js} +1 -1
  11. package/dist/{client/_astro/PageContext.miTsIqVo.js → _astro/PageContext.BUbWpNW2.js} +1 -1
  12. package/dist/{client/_astro/PageSidebarBody.B0AJe8Hg.js → _astro/PageSidebarBody.CDWZuFeK.js} +1 -1
  13. package/dist/{client/_astro/PageToggle.CMZ3C1v1.js → _astro/PageToggle.Dnbvoa7R.js} +1 -1
  14. package/dist/{client/_astro/SearchInput.DhHo7yPx.js → _astro/SearchInput.BNt7BTX_.js} +1 -1
  15. package/dist/{client/_astro/SectionGallery.3ABpQwE4.js → _astro/SectionGallery.Dwb-QA5z.js} +1 -1
  16. package/dist/{client/_astro/Toolbar.CroDQcyv.js → _astro/Toolbar.DNd68Ck-.js} +1 -1
  17. package/dist/{client/_astro/ToolbarContent.UH3ZRlHp.js → _astro/ToolbarContent.C58gpKLu.js} +1 -1
  18. package/dist/{client/_astro/angle-left-icon.teo8GC0v.js → _astro/angle-left-icon.CfKwuSCS.js} +1 -1
  19. package/dist/{client/_astro/bars-icon.Dk6ua1rr.js → _astro/bars-icon.wdJgEs3A.js} +1 -1
  20. package/dist/_astro/client.DN8ES6L5.js +1 -0
  21. package/dist/{client/_astro/divider.tlrBPkzg.js → _astro/divider.BLVh3KnH.js} +1 -1
  22. package/dist/{client/_astro/github-icon.ByC5XEPt.js → _astro/github-icon.DzpohUp_.js} +1 -1
  23. package/dist/{client/_astro/index.DYVB4vTo.js → _astro/index.jm6QVFFy.js} +1 -1
  24. package/dist/{client/_astro/link-icon.BNHnRn73.js → _astro/patternfly_charts.Dp3KzAU6.js} +24 -24
  25. package/dist/_routes.json +20 -0
  26. package/dist/_worker.js/_@astrojs-ssr-adapter.mjs +2 -0
  27. package/dist/_worker.js/_astro-internal_middleware.mjs +21 -0
  28. package/dist/_worker.js/_noop-actions.mjs +4 -0
  29. package/dist/{server/chunks/AutoLinkHeader_C2GD0g-K.mjs → _worker.js/chunks/AutoLinkHeader_DLgn_YRm.mjs} +13 -14
  30. package/dist/{server/chunks/Button_BKhHR-ak.mjs → _worker.js/chunks/Button_CBcC0ViE.mjs} +83 -13
  31. package/dist/{server/chunks/CSSTable_B8tlH3gz.mjs → _worker.js/chunks/CSSTable_C1dV02qV.mjs} +3 -3
  32. package/dist/_worker.js/chunks/DocsTables_Br4g5x5_.mjs +20 -0
  33. package/dist/_worker.js/chunks/PropsTables_Dcd7znAq.mjs +6628 -0
  34. package/dist/_worker.js/chunks/_@astrojs-ssr-adapter_IMtcR503.mjs +1082 -0
  35. package/dist/_worker.js/chunks/angle-down-icon_VyCXUC7F.mjs +3686 -0
  36. package/dist/_worker.js/chunks/astro/server_YsSSp7Ny.mjs +7278 -0
  37. package/dist/_worker.js/chunks/astro-designed-error-pages_MEt0E9xn.mjs +928 -0
  38. package/dist/_worker.js/chunks/cloudflare-kv-binding_DMly_2Gl.mjs +107 -0
  39. package/dist/{server/chunks/_@astrojs-ssr-adapter_CbICuCdt.mjs → _worker.js/chunks/index_BE2AHcwI.mjs} +1295 -1817
  40. package/dist/_worker.js/chunks/index_CBCp_CJ0.mjs +57 -0
  41. package/dist/_worker.js/chunks/noop-middleware_CMUpAQ6F.mjs +10 -0
  42. package/dist/_worker.js/chunks/parse_EttCPxrw.mjs +271 -0
  43. package/dist/{server/chunks/path_Cvt6sEOY.mjs → _worker.js/chunks/path_C-ZOwaTP.mjs} +2 -1
  44. package/dist/{server/entry.mjs → _worker.js/index.js} +13 -19
  45. package/dist/_worker.js/manifest_0KWZohUX.mjs +100 -0
  46. package/dist/_worker.js/pages/_image.astro.mjs +24 -0
  47. package/dist/_worker.js/pages/_section_/_page_/_---tab_.astro.mjs +1 -0
  48. package/dist/_worker.js/pages/index.astro.mjs +1 -0
  49. package/dist/{server → _worker.js}/pages/props.astro.mjs +3 -2
  50. package/dist/_worker.js/renderers.mjs +484 -0
  51. package/dist/cli/cli.js +46 -12
  52. package/dist/{client/components/accordion/react → components/accordion}/index.html +14 -64
  53. package/dist/{client/components/accordion → components/accordion/react}/index.html +14 -64
  54. package/dist/components/all-components/index.html +47 -0
  55. package/dist/design-foundations/typography/index.html +198 -0
  56. package/dist/{client/design-foundations → design-foundations}/usage-and-behavior/index.html +4 -54
  57. package/dist/get-started/contribute/index.html +94 -0
  58. package/dist/index.html +43 -0
  59. package/package.json +12 -8
  60. package/public/.assetsignore +2 -0
  61. package/src/components/DocsTables.astro +28 -0
  62. package/src/pages/[section]/[...page].astro +7 -11
  63. package/src/pages/[section]/[page]/[...tab].astro +3 -11
  64. package/src/pages/props.ts +2 -2
  65. package/wrangler.jsonc +14 -0
  66. package/dist/client/_astro/CSSTable.DC79W1Ct.js +0 -1
  67. package/dist/client/_astro/ClientRouter.astro_astro_type_script_index_0_lang.Cainpjm5.js +0 -1
  68. package/dist/client/_astro/client.zs76E0tG.js +0 -1
  69. package/dist/client/components/all-components/index.html +0 -97
  70. package/dist/client/design-foundations/typography/index.html +0 -248
  71. package/dist/client/get-started/contribute/index.html +0 -144
  72. package/dist/client/index.html +0 -43
  73. package/dist/server/_@astrojs-ssr-adapter.mjs +0 -1
  74. package/dist/server/_noop-middleware.mjs +0 -3
  75. package/dist/server/chunks/PropsTables_PVzRHJNB.mjs +0 -1750
  76. package/dist/server/chunks/_astro_assets_DaYumpRZ.mjs +0 -1507
  77. package/dist/server/chunks/angle-down-icon_BO1Ed-9Z.mjs +0 -3288
  78. package/dist/server/chunks/astro/server_Cl9jPh4p.mjs +0 -2859
  79. package/dist/server/chunks/astro-designed-error-pages_BFveJFnQ.mjs +0 -282
  80. package/dist/server/chunks/consts_BmVDRGlB.mjs +0 -32
  81. package/dist/server/chunks/sharp_CbOL3WDk.mjs +0 -88
  82. package/dist/server/manifest_DsbMfV1U.mjs +0 -102
  83. package/dist/server/pages/_image.astro.mjs +0 -132
  84. package/dist/server/renderers.mjs +0 -308
  85. /package/dist/{client/PF-HorizontalLogo-Color.svg → PF-HorizontalLogo-Color.svg} +0 -0
  86. /package/dist/{client/PF-HorizontalLogo-Reverse.svg → PF-HorizontalLogo-Reverse.svg} +0 -0
  87. /package/dist/{client/_astro → _astro}/LiveExample.CxJsMvEq.css +0 -0
  88. /package/dist/{client/_astro → _astro}/RedHatDisplayVF-Italic.CRpusWc8.woff2 +0 -0
  89. /package/dist/{client/_astro → _astro}/RedHatDisplayVF.CYDHf1NI.woff2 +0 -0
  90. /package/dist/{client/_astro → _astro}/RedHatMonoVF-Italic.DGQo2ogW.woff2 +0 -0
  91. /package/dist/{client/_astro → _astro}/RedHatMonoVF.C4fMH6Vz.woff2 +0 -0
  92. /package/dist/{client/_astro → _astro}/RedHatTextVF-Italic.Dkj_WqbA.woff2 +0 -0
  93. /package/dist/{client/_astro → _astro}/RedHatTextVF.wYvZ7prR.woff2 +0 -0
  94. /package/dist/{client/_astro → _astro}/_page_.Chv_bGyU.css +0 -0
  95. /package/dist/{client/_astro → _astro}/_page_.CtheD08_.css +0 -0
  96. /package/dist/{client/_astro → _astro}/_page_.D1z73Byz.css +0 -0
  97. /package/dist/{client/_astro → _astro}/_page_.DxJDkZPc.css +0 -0
  98. /package/dist/{client/_astro → _astro}/fa-solid-900.DguXoeIz.woff2 +0 -0
  99. /package/dist/{client/_astro → _astro}/index.BQFV5hT1.js +0 -0
  100. /package/dist/{client/_astro → _astro}/index.CAChmxYj.js +0 -0
  101. /package/dist/{client/_astro → _astro}/index.eCxJ45ll.js +0 -0
  102. /package/dist/{client/_astro → _astro}/page.BTC3Kf3x.js +0 -0
  103. /package/dist/{client/_astro → _astro}/pf-v6-pficon.Dy6oiu9u.woff2 +0 -0
  104. /package/dist/{server/chunks/Accordion_BJka4Qvb.mjs → _worker.js/chunks/Accordion_CQUal4ef.mjs} +0 -0
  105. /package/dist/{server/chunks/Accordion_BQIphkaZ.mjs → _worker.js/chunks/Accordion_R7bP3pwr.mjs} +0 -0
  106. /package/dist/{server/chunks/AllComponents_CRhgTsiT.mjs → _worker.js/chunks/AllComponents_BDKlE-WJ.mjs} +0 -0
  107. /package/dist/{server/chunks/AllComponents_CjOtwUH6.mjs → _worker.js/chunks/AllComponents_DWDph25H.mjs} +0 -0
  108. /package/dist/{server/chunks/_astro_data-layer-content_D4Ib_RjR.mjs → _worker.js/chunks/_astro_assets_CfTVyruF.mjs} +0 -0
  109. /package/dist/{server/chunks/content-assets_DleWbedO.mjs → _worker.js/chunks/_astro_data-layer-content_CgXoS6Mm.mjs} +0 -0
  110. /package/dist/{server/chunks/content-modules_fX1c2JRG.mjs → _worker.js/chunks/content-assets_XqCgPAV2.mjs} +0 -0
  111. /package/dist/{server/pages/_section_/_---page_.astro.mjs → _worker.js/chunks/content-modules_BbCqcGJp.mjs} +0 -0
  112. /package/dist/{server/pages/_section_/_page_/_---tab_.astro.mjs → _worker.js/chunks/sharp_MEdXG7Td.mjs} +0 -0
  113. /package/dist/{server/pages/index.astro.mjs → _worker.js/pages/_section_/_---page_.astro.mjs} +0 -0
  114. /package/dist/{client/avatarImg.svg → avatarImg.svg} +0 -0
  115. /package/dist/{client/avatarImgDark.svg → avatarImgDark.svg} +0 -0
  116. /package/dist/{client/content → content}/typography/line-height.png +0 -0
  117. /package/dist/{client/favicon.svg → favicon.svg} +0 -0
@@ -1,2859 +0,0 @@
1
- import { bold } from 'kleur/colors';
2
- import { clsx } from 'clsx';
3
- import { escape } from 'html-escaper';
4
- import { encodeHexUpperCase, encodeBase64, decodeBase64, decodeHex } from '@oslojs/encoding';
5
- import 'cssesc';
6
-
7
- function normalizeLF(code) {
8
- return code.replace(/\r\n|\r(?!\n)|\n/g, "\n");
9
- }
10
-
11
- function codeFrame(src, loc) {
12
- if (!loc || loc.line === void 0 || loc.column === void 0) {
13
- return "";
14
- }
15
- const lines = normalizeLF(src).split("\n").map((ln) => ln.replace(/\t/g, " "));
16
- const visibleLines = [];
17
- for (let n = -2; n <= 2; n++) {
18
- if (lines[loc.line + n]) visibleLines.push(loc.line + n);
19
- }
20
- let gutterWidth = 0;
21
- for (const lineNo of visibleLines) {
22
- let w = `> ${lineNo}`;
23
- if (w.length > gutterWidth) gutterWidth = w.length;
24
- }
25
- let output = "";
26
- for (const lineNo of visibleLines) {
27
- const isFocusedLine = lineNo === loc.line - 1;
28
- output += isFocusedLine ? "> " : " ";
29
- output += `${lineNo + 1} | ${lines[lineNo]}
30
- `;
31
- if (isFocusedLine)
32
- output += `${Array.from({ length: gutterWidth }).join(" ")} | ${Array.from({
33
- length: loc.column
34
- }).join(" ")}^
35
- `;
36
- }
37
- return output;
38
- }
39
-
40
- class AstroError extends Error {
41
- loc;
42
- title;
43
- hint;
44
- frame;
45
- type = "AstroError";
46
- constructor(props, options) {
47
- const { name, title, message, stack, location, hint, frame } = props;
48
- super(message, options);
49
- this.title = title;
50
- this.name = name;
51
- if (message) this.message = message;
52
- this.stack = stack ? stack : this.stack;
53
- this.loc = location;
54
- this.hint = hint;
55
- this.frame = frame;
56
- }
57
- setLocation(location) {
58
- this.loc = location;
59
- }
60
- setName(name) {
61
- this.name = name;
62
- }
63
- setMessage(message) {
64
- this.message = message;
65
- }
66
- setHint(hint) {
67
- this.hint = hint;
68
- }
69
- setFrame(source, location) {
70
- this.frame = codeFrame(source, location);
71
- }
72
- static is(err) {
73
- return err.type === "AstroError";
74
- }
75
- }
76
- class AstroUserError extends Error {
77
- type = "AstroUserError";
78
- /**
79
- * A message that explains to the user how they can fix the error.
80
- */
81
- hint;
82
- name = "AstroUserError";
83
- constructor(message, hint) {
84
- super();
85
- this.message = message;
86
- this.hint = hint;
87
- }
88
- static is(err) {
89
- return err.type === "AstroUserError";
90
- }
91
- }
92
-
93
- const ClientAddressNotAvailable = {
94
- name: "ClientAddressNotAvailable",
95
- title: "`Astro.clientAddress` is not available in current adapter.",
96
- message: (adapterName) => `\`Astro.clientAddress\` is not available in the \`${adapterName}\` adapter. File an issue with the adapter to add support.`
97
- };
98
- const PrerenderClientAddressNotAvailable = {
99
- name: "PrerenderClientAddressNotAvailable",
100
- title: "`Astro.clientAddress` cannot be used inside prerendered routes.",
101
- message: `\`Astro.clientAddress\` cannot be used inside prerendered routes`
102
- };
103
- const StaticClientAddressNotAvailable = {
104
- name: "StaticClientAddressNotAvailable",
105
- title: "`Astro.clientAddress` is not available in prerendered pages.",
106
- message: "`Astro.clientAddress` is only available on pages that are server-rendered.",
107
- hint: "See https://docs.astro.build/en/guides/on-demand-rendering/ for more information on how to enable SSR."
108
- };
109
- const NoMatchingStaticPathFound = {
110
- name: "NoMatchingStaticPathFound",
111
- title: "No static path found for requested path.",
112
- message: (pathName) => `A \`getStaticPaths()\` route pattern was matched, but no matching static path was found for requested path \`${pathName}\`.`,
113
- hint: (possibleRoutes) => `Possible dynamic routes being matched: ${possibleRoutes.join(", ")}.`
114
- };
115
- const OnlyResponseCanBeReturned = {
116
- name: "OnlyResponseCanBeReturned",
117
- title: "Invalid type returned by Astro page.",
118
- message: (route, returnedValue) => `Route \`${route ? route : ""}\` returned a \`${returnedValue}\`. Only a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from Astro files.`,
119
- hint: "See https://docs.astro.build/en/guides/on-demand-rendering/#response for more information."
120
- };
121
- const MissingMediaQueryDirective = {
122
- name: "MissingMediaQueryDirective",
123
- title: "Missing value for `client:media` directive.",
124
- message: 'Media query not provided for `client:media` directive. A media query similar to `client:media="(max-width: 600px)"` must be provided'
125
- };
126
- const NoMatchingRenderer = {
127
- name: "NoMatchingRenderer",
128
- title: "No matching renderer found.",
129
- message: (componentName, componentExtension, plural, validRenderersCount) => `Unable to render \`${componentName}\`.
130
-
131
- ${validRenderersCount > 0 ? `There ${plural ? "are" : "is"} ${validRenderersCount} renderer${plural ? "s" : ""} configured in your \`astro.config.mjs\` file,
132
- but ${plural ? "none were" : "it was not"} able to server-side render \`${componentName}\`.` : `No valid renderer was found ${componentExtension ? `for the \`.${componentExtension}\` file extension.` : `for this file extension.`}`}`,
133
- hint: (probableRenderers) => `Did you mean to enable the ${probableRenderers} integration?
134
-
135
- See https://docs.astro.build/en/guides/framework-components/ for more information on how to install and configure integrations.`
136
- };
137
- const NoClientOnlyHint = {
138
- name: "NoClientOnlyHint",
139
- title: "Missing hint on client:only directive.",
140
- message: (componentName) => `Unable to render \`${componentName}\`. When using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.`,
141
- hint: (probableRenderers) => `Did you mean to pass \`client:only="${probableRenderers}"\`? See https://docs.astro.build/en/reference/directives-reference/#clientonly for more information on client:only`
142
- };
143
- const InvalidGetStaticPathsEntry = {
144
- name: "InvalidGetStaticPathsEntry",
145
- title: "Invalid entry inside getStaticPath's return value",
146
- message: (entryType) => `Invalid entry returned by getStaticPaths. Expected an object, got \`${entryType}\``,
147
- hint: "If you're using a `.map` call, you might be looking for `.flatMap()` instead. See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
148
- };
149
- const InvalidGetStaticPathsReturn = {
150
- name: "InvalidGetStaticPathsReturn",
151
- title: "Invalid value returned by getStaticPaths.",
152
- message: (returnType) => `Invalid type returned by \`getStaticPaths\`. Expected an \`array\`, got \`${returnType}\``,
153
- hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
154
- };
155
- const GetStaticPathsExpectedParams = {
156
- name: "GetStaticPathsExpectedParams",
157
- title: "Missing params property on `getStaticPaths` route.",
158
- message: "Missing or empty required `params` property on `getStaticPaths` route.",
159
- hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
160
- };
161
- const GetStaticPathsInvalidRouteParam = {
162
- name: "GetStaticPathsInvalidRouteParam",
163
- title: "Invalid value for `getStaticPaths` route parameter.",
164
- message: (key, value, valueType) => `Invalid getStaticPaths route parameter for \`${key}\`. Expected undefined, a string or a number, received \`${valueType}\` (\`${value}\`)`,
165
- hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
166
- };
167
- const GetStaticPathsRequired = {
168
- name: "GetStaticPathsRequired",
169
- title: "`getStaticPaths()` function required for dynamic routes.",
170
- message: "`getStaticPaths()` function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route.",
171
- hint: `See https://docs.astro.build/en/guides/routing/#dynamic-routes for more information on dynamic routes.
172
-
173
- If you meant for this route to be server-rendered, set \`export const prerender = false;\` in the page.`
174
- };
175
- const ReservedSlotName = {
176
- name: "ReservedSlotName",
177
- title: "Invalid slot name.",
178
- message: (slotName) => `Unable to create a slot named \`${slotName}\`. \`${slotName}\` is a reserved slot name. Please update the name of this slot.`
179
- };
180
- const NoMatchingImport = {
181
- name: "NoMatchingImport",
182
- title: "No import found for component.",
183
- message: (componentName) => `Could not render \`${componentName}\`. No matching import has been found for \`${componentName}\`.`,
184
- hint: "Please make sure the component is properly imported."
185
- };
186
- const InvalidComponentArgs = {
187
- name: "InvalidComponentArgs",
188
- title: "Invalid component arguments.",
189
- message: (name) => `Invalid arguments passed to${name ? ` <${name}>` : ""} component.`,
190
- hint: "Astro components cannot be rendered directly via function call, such as `Component()` or `{items.map(Component)}`."
191
- };
192
- const PageNumberParamNotFound = {
193
- name: "PageNumberParamNotFound",
194
- title: "Page number param not found.",
195
- message: (paramName) => `[paginate()] page number param \`${paramName}\` not found in your filepath.`,
196
- hint: "Rename your file to `[page].astro` or `[...page].astro`."
197
- };
198
- const ImageMissingAlt = {
199
- name: "ImageMissingAlt",
200
- title: 'Image missing required "alt" property.',
201
- message: 'Image missing "alt" property. "alt" text is required to describe important images on the page.',
202
- hint: 'Use an empty string ("") for decorative images.'
203
- };
204
- const InvalidImageService = {
205
- name: "InvalidImageService",
206
- title: "Error while loading image service.",
207
- message: "There was an error loading the configured image service. Please see the stack trace for more information."
208
- };
209
- const MissingImageDimension = {
210
- name: "MissingImageDimension",
211
- title: "Missing image dimensions",
212
- message: (missingDimension, imageURL) => `Missing ${missingDimension === "both" ? "width and height attributes" : `${missingDimension} attribute`} for ${imageURL}. When using remote images, both dimensions are required in order to avoid CLS.`,
213
- hint: "If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets). You can also use `inferSize={true}` for remote images to get the original dimensions."
214
- };
215
- const FailedToFetchRemoteImageDimensions = {
216
- name: "FailedToFetchRemoteImageDimensions",
217
- title: "Failed to retrieve remote image dimensions",
218
- message: (imageURL) => `Failed to get the dimensions for ${imageURL}.`,
219
- hint: "Verify your remote image URL is accurate, and that you are not using `inferSize` with a file located in your `public/` folder."
220
- };
221
- const UnsupportedImageFormat = {
222
- name: "UnsupportedImageFormat",
223
- title: "Unsupported image format",
224
- message: (format, imagePath, supportedFormats) => `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join(
225
- ", "
226
- )} are supported by our image services.`,
227
- hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for."
228
- };
229
- const UnsupportedImageConversion = {
230
- name: "UnsupportedImageConversion",
231
- title: "Unsupported image conversion",
232
- message: "Converting between vector (such as SVGs) and raster (such as PNGs and JPEGs) images is not currently supported."
233
- };
234
- const PrerenderDynamicEndpointPathCollide = {
235
- name: "PrerenderDynamicEndpointPathCollide",
236
- title: "Prerendered dynamic endpoint has path collision.",
237
- message: (pathname) => `Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, or add an additional extension to the endpoint's filename.`,
238
- hint: (filename) => `Rename \`${filename}\` to \`${filename.replace(/\.(?:js|ts)/, (m) => `.json` + m)}\``
239
- };
240
- const ExpectedImage = {
241
- name: "ExpectedImage",
242
- title: "Expected src to be an image.",
243
- message: (src, typeofOptions, fullOptions) => `Expected \`src\` property for \`getImage\` or \`<Image />\` to be either an ESM imported image or a string with the path of a remote image. Received \`${src}\` (type: \`${typeofOptions}\`).
244
-
245
- Full serialized options received: \`${fullOptions}\`.`,
246
- hint: "This error can often happen because of a wrong path. Make sure the path to your image is correct. If you're passing an async function, make sure to call and await it."
247
- };
248
- const ExpectedImageOptions = {
249
- name: "ExpectedImageOptions",
250
- title: "Expected image options.",
251
- message: (options) => `Expected getImage() parameter to be an object. Received \`${options}\`.`
252
- };
253
- const ExpectedNotESMImage = {
254
- name: "ExpectedNotESMImage",
255
- title: "Expected image options, not an ESM-imported image.",
256
- message: "An ESM-imported image cannot be passed directly to `getImage()`. Instead, pass an object with the image in the `src` property.",
257
- hint: "Try changing `getImage(myImage)` to `getImage({ src: myImage })`"
258
- };
259
- const IncompatibleDescriptorOptions = {
260
- name: "IncompatibleDescriptorOptions",
261
- title: "Cannot set both `densities` and `widths`",
262
- message: "Only one of `densities` or `widths` can be specified. In most cases, you'll probably want to use only `widths` if you require specific widths.",
263
- hint: "Those attributes are used to construct a `srcset` attribute, which cannot have both `x` and `w` descriptors."
264
- };
265
- const NoImageMetadata = {
266
- name: "NoImageMetadata",
267
- title: "Could not process image metadata.",
268
- message: (imagePath) => `Could not process image metadata${imagePath ? ` for \`${imagePath}\`` : ""}.`,
269
- hint: "This is often caused by a corrupted or malformed image. Re-exporting the image from your image editor may fix this issue."
270
- };
271
- const ResponseSentError = {
272
- name: "ResponseSentError",
273
- title: "Unable to set response.",
274
- message: "The response has already been sent to the browser and cannot be altered."
275
- };
276
- const MiddlewareNoDataOrNextCalled = {
277
- name: "MiddlewareNoDataOrNextCalled",
278
- title: "The middleware didn't return a `Response`.",
279
- message: "Make sure your middleware returns a `Response` object, either directly or by returning the `Response` from calling the `next` function."
280
- };
281
- const MiddlewareNotAResponse = {
282
- name: "MiddlewareNotAResponse",
283
- title: "The middleware returned something that is not a `Response` object.",
284
- message: "Any data returned from middleware must be a valid `Response` object."
285
- };
286
- const EndpointDidNotReturnAResponse = {
287
- name: "EndpointDidNotReturnAResponse",
288
- title: "The endpoint did not return a `Response`.",
289
- message: "An endpoint must return either a `Response`, or a `Promise` that resolves with a `Response`."
290
- };
291
- const LocalsNotAnObject = {
292
- name: "LocalsNotAnObject",
293
- title: "Value assigned to `locals` is not accepted.",
294
- message: "`locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted.",
295
- hint: "If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`."
296
- };
297
- const LocalsReassigned = {
298
- name: "LocalsReassigned",
299
- title: "`locals` must not be reassigned.",
300
- message: "`locals` can not be assigned directly.",
301
- hint: "Set a `locals` property instead."
302
- };
303
- const AstroResponseHeadersReassigned = {
304
- name: "AstroResponseHeadersReassigned",
305
- title: "`Astro.response.headers` must not be reassigned.",
306
- message: "Individual headers can be added to and removed from `Astro.response.headers`, but it must not be replaced with another instance of `Headers` altogether.",
307
- hint: "Consider using `Astro.response.headers.add()`, and `Astro.response.headers.delete()`."
308
- };
309
- const LocalImageUsedWrongly = {
310
- name: "LocalImageUsedWrongly",
311
- title: "Local images must be imported.",
312
- message: (imageFilePath) => `\`Image\`'s and \`getImage\`'s \`src\` parameter must be an imported image or an URL, it cannot be a string filepath. Received \`${imageFilePath}\`.`,
313
- hint: "If you want to use an image from your `src` folder, you need to either import it or if the image is coming from a content collection, use the [image() schema helper](https://docs.astro.build/en/guides/images/#images-in-content-collections). See https://docs.astro.build/en/guides/images/#src-required for more information on the `src` property."
314
- };
315
- const AstroGlobUsedOutside = {
316
- name: "AstroGlobUsedOutside",
317
- title: "Astro.glob() used outside of an Astro file.",
318
- message: (globStr) => `\`Astro.glob(${globStr})\` can only be used in \`.astro\` files. \`import.meta.glob(${globStr})\` can be used instead to achieve a similar result.`,
319
- hint: "See Vite's documentation on `import.meta.glob` for more information: https://vite.dev/guide/features.html#glob-import"
320
- };
321
- const AstroGlobNoMatch = {
322
- name: "AstroGlobNoMatch",
323
- title: "Astro.glob() did not match any files.",
324
- message: (globStr) => `\`Astro.glob(${globStr})\` did not return any matching files.`,
325
- hint: "Check the pattern for typos."
326
- };
327
- const MissingSharp = {
328
- name: "MissingSharp",
329
- title: "Could not find Sharp.",
330
- message: "Could not find Sharp. Please install Sharp (`sharp`) manually into your project or migrate to another image service.",
331
- hint: "See Sharp's installation instructions for more information: https://sharp.pixelplumbing.com/install. If you are not relying on `astro:assets` to optimize, transform, or process any images, you can configure a passthrough image service instead of installing Sharp. See https://docs.astro.build/en/reference/errors/missing-sharp for more information.\n\nSee https://docs.astro.build/en/guides/images/#default-image-service for more information on how to migrate to another image service."
332
- };
333
- const i18nNoLocaleFoundInPath = {
334
- name: "i18nNoLocaleFoundInPath",
335
- title: "The path doesn't contain any locale",
336
- message: "You tried to use an i18n utility on a path that doesn't contain any locale. You can use `pathHasLocale` first to determine if the path has a locale."
337
- };
338
- const RewriteWithBodyUsed = {
339
- name: "RewriteWithBodyUsed",
340
- title: "Cannot use Astro.rewrite after the request body has been read",
341
- message: "Astro.rewrite() cannot be used if the request body has already been read. If you need to read the body, first clone the request."
342
- };
343
- const ForbiddenRewrite = {
344
- name: "ForbiddenRewrite",
345
- title: "Forbidden rewrite to a static route.",
346
- message: (from, to, component) => `You tried to rewrite the on-demand route '${from}' with the static route '${to}', when using the 'server' output.
347
-
348
- The static route '${to}' is rendered by the component
349
- '${component}', which is marked as prerendered. This is a forbidden operation because during the build the component '${component}' is compiled to an
350
- HTML file, which can't be retrieved at runtime by Astro.`,
351
- hint: (component) => `Add \`export const prerender = false\` to the component '${component}', or use a Astro.redirect().`
352
- };
353
- const UnknownContentCollectionError = {
354
- name: "UnknownContentCollectionError",
355
- title: "Unknown Content Collection Error."
356
- };
357
- const RenderUndefinedEntryError = {
358
- name: "RenderUndefinedEntryError",
359
- title: "Attempted to render an undefined content collection entry.",
360
- hint: "Check if the entry is undefined before passing it to `render()`"
361
- };
362
- const SessionStorageInitError = {
363
- name: "SessionStorageInitError",
364
- title: "Session storage could not be initialized.",
365
- message: (error, driver) => `Error when initializing session storage${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``,
366
- hint: "For more information, see https://docs.astro.build/en/reference/experimental-flags/sessions/"
367
- };
368
- const SessionStorageSaveError = {
369
- name: "SessionStorageSaveError",
370
- title: "Session data could not be saved.",
371
- message: (error, driver) => `Error when saving session data${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``,
372
- hint: "For more information, see https://docs.astro.build/en/reference/experimental-flags/sessions/"
373
- };
374
-
375
- function validateArgs(args) {
376
- if (args.length !== 3) return false;
377
- if (!args[0] || typeof args[0] !== "object") return false;
378
- return true;
379
- }
380
- function baseCreateComponent(cb, moduleId, propagation) {
381
- const name = moduleId?.split("/").pop()?.replace(".astro", "") ?? "";
382
- const fn = (...args) => {
383
- if (!validateArgs(args)) {
384
- throw new AstroError({
385
- ...InvalidComponentArgs,
386
- message: InvalidComponentArgs.message(name)
387
- });
388
- }
389
- return cb(...args);
390
- };
391
- Object.defineProperty(fn, "name", { value: name, writable: false });
392
- fn.isAstroComponentFactory = true;
393
- fn.moduleId = moduleId;
394
- fn.propagation = propagation;
395
- return fn;
396
- }
397
- function createComponentWithOptions(opts) {
398
- const cb = baseCreateComponent(opts.factory, opts.moduleId, opts.propagation);
399
- return cb;
400
- }
401
- function createComponent(arg1, moduleId, propagation) {
402
- if (typeof arg1 === "function") {
403
- return baseCreateComponent(arg1, moduleId, propagation);
404
- } else {
405
- return createComponentWithOptions(arg1);
406
- }
407
- }
408
-
409
- const ASTRO_VERSION = "5.4.1";
410
- const REROUTE_DIRECTIVE_HEADER = "X-Astro-Reroute";
411
- const REWRITE_DIRECTIVE_HEADER_KEY = "X-Astro-Rewrite";
412
- const REWRITE_DIRECTIVE_HEADER_VALUE = "yes";
413
- const NOOP_MIDDLEWARE_HEADER = "X-Astro-Noop";
414
- const ROUTE_TYPE_HEADER = "X-Astro-Route-Type";
415
- const DEFAULT_404_COMPONENT = "astro-default-404.astro";
416
- const REROUTABLE_STATUS_CODES = [404, 500];
417
- const clientAddressSymbol = Symbol.for("astro.clientAddress");
418
- const originPathnameSymbol = Symbol.for("astro.originPathname");
419
- const responseSentSymbol = Symbol.for("astro.responseSent");
420
-
421
- function createAstroGlobFn() {
422
- const globHandler = (importMetaGlobResult) => {
423
- console.warn(`Astro.glob is deprecated and will be removed in a future major version of Astro.
424
- Use import.meta.glob instead: https://vitejs.dev/guide/features.html#glob-import`);
425
- if (typeof importMetaGlobResult === "string") {
426
- throw new AstroError({
427
- ...AstroGlobUsedOutside,
428
- message: AstroGlobUsedOutside.message(JSON.stringify(importMetaGlobResult))
429
- });
430
- }
431
- let allEntries = [...Object.values(importMetaGlobResult)];
432
- if (allEntries.length === 0) {
433
- throw new AstroError({
434
- ...AstroGlobNoMatch,
435
- message: AstroGlobNoMatch.message(JSON.stringify(importMetaGlobResult))
436
- });
437
- }
438
- return Promise.all(allEntries.map((fn) => fn()));
439
- };
440
- return globHandler;
441
- }
442
- function createAstro(site) {
443
- return {
444
- // TODO: this is no longer necessary for `Astro.site`
445
- // but it somehow allows working around caching issues in content collections for some tests
446
- site: void 0,
447
- generator: `Astro v${ASTRO_VERSION}`,
448
- glob: createAstroGlobFn()
449
- };
450
- }
451
-
452
- async function renderEndpoint(mod, context, isPrerendered, logger) {
453
- const { request, url } = context;
454
- const method = request.method.toUpperCase();
455
- let handler = mod[method] ?? mod["ALL"];
456
- if (!handler && method === "HEAD" && mod["GET"]) {
457
- handler = mod["GET"];
458
- }
459
- if (isPrerendered && !["GET", "HEAD"].includes(method)) {
460
- logger.warn(
461
- "router",
462
- `${url.pathname} ${bold(
463
- method
464
- )} requests are not available in static endpoints. Mark this page as server-rendered (\`export const prerender = false;\`) or update your config to \`output: 'server'\` to make all your pages server-rendered by default.`
465
- );
466
- }
467
- if (handler === void 0) {
468
- logger.warn(
469
- "router",
470
- `No API Route handler exists for the method "${method}" for the route "${url.pathname}".
471
- Found handlers: ${Object.keys(mod).map((exp) => JSON.stringify(exp)).join(", ")}
472
- ` + ("all" in mod ? `One of the exported handlers is "all" (lowercase), did you mean to export 'ALL'?
473
- ` : "")
474
- );
475
- return new Response(null, { status: 404 });
476
- }
477
- if (typeof handler !== "function") {
478
- logger.error(
479
- "router",
480
- `The route "${url.pathname}" exports a value for the method "${method}", but it is of the type ${typeof handler} instead of a function.`
481
- );
482
- return new Response(null, { status: 500 });
483
- }
484
- let response = await handler.call(mod, context);
485
- if (!response || response instanceof Response === false) {
486
- throw new AstroError(EndpointDidNotReturnAResponse);
487
- }
488
- if (REROUTABLE_STATUS_CODES.includes(response.status)) {
489
- try {
490
- response.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
491
- } catch (err) {
492
- if (err.message?.includes("immutable")) {
493
- response = new Response(response.body, response);
494
- response.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
495
- } else {
496
- throw err;
497
- }
498
- }
499
- }
500
- if (method === "HEAD") {
501
- return new Response(null, response);
502
- }
503
- return response;
504
- }
505
-
506
- function isPromise(value) {
507
- return !!value && typeof value === "object" && "then" in value && typeof value.then === "function";
508
- }
509
- async function* streamAsyncIterator(stream) {
510
- const reader = stream.getReader();
511
- try {
512
- while (true) {
513
- const { done, value } = await reader.read();
514
- if (done) return;
515
- yield value;
516
- }
517
- } finally {
518
- reader.releaseLock();
519
- }
520
- }
521
-
522
- const escapeHTML = escape;
523
- class HTMLBytes extends Uint8Array {
524
- }
525
- Object.defineProperty(HTMLBytes.prototype, Symbol.toStringTag, {
526
- get() {
527
- return "HTMLBytes";
528
- }
529
- });
530
- class HTMLString extends String {
531
- get [Symbol.toStringTag]() {
532
- return "HTMLString";
533
- }
534
- }
535
- const markHTMLString = (value) => {
536
- if (value instanceof HTMLString) {
537
- return value;
538
- }
539
- if (typeof value === "string") {
540
- return new HTMLString(value);
541
- }
542
- return value;
543
- };
544
- function isHTMLString(value) {
545
- return Object.prototype.toString.call(value) === "[object HTMLString]";
546
- }
547
- function markHTMLBytes(bytes) {
548
- return new HTMLBytes(bytes);
549
- }
550
- function hasGetReader(obj) {
551
- return typeof obj.getReader === "function";
552
- }
553
- async function* unescapeChunksAsync(iterable) {
554
- if (hasGetReader(iterable)) {
555
- for await (const chunk of streamAsyncIterator(iterable)) {
556
- yield unescapeHTML(chunk);
557
- }
558
- } else {
559
- for await (const chunk of iterable) {
560
- yield unescapeHTML(chunk);
561
- }
562
- }
563
- }
564
- function* unescapeChunks(iterable) {
565
- for (const chunk of iterable) {
566
- yield unescapeHTML(chunk);
567
- }
568
- }
569
- function unescapeHTML(str) {
570
- if (!!str && typeof str === "object") {
571
- if (str instanceof Uint8Array) {
572
- return markHTMLBytes(str);
573
- } else if (str instanceof Response && str.body) {
574
- const body = str.body;
575
- return unescapeChunksAsync(body);
576
- } else if (typeof str.then === "function") {
577
- return Promise.resolve(str).then((value) => {
578
- return unescapeHTML(value);
579
- });
580
- } else if (str[Symbol.for("astro:slot-string")]) {
581
- return str;
582
- } else if (Symbol.iterator in str) {
583
- return unescapeChunks(str);
584
- } else if (Symbol.asyncIterator in str || hasGetReader(str)) {
585
- return unescapeChunksAsync(str);
586
- }
587
- }
588
- return markHTMLString(str);
589
- }
590
-
591
- const RenderInstructionSymbol = Symbol.for("astro:render");
592
- function createRenderInstruction(instruction) {
593
- return Object.defineProperty(instruction, RenderInstructionSymbol, {
594
- value: true
595
- });
596
- }
597
- function isRenderInstruction(chunk) {
598
- return chunk && typeof chunk === "object" && chunk[RenderInstructionSymbol];
599
- }
600
-
601
- const PROP_TYPE = {
602
- Value: 0,
603
- JSON: 1,
604
- // Actually means Array
605
- RegExp: 2,
606
- Date: 3,
607
- Map: 4,
608
- Set: 5,
609
- BigInt: 6,
610
- URL: 7,
611
- Uint8Array: 8,
612
- Uint16Array: 9,
613
- Uint32Array: 10,
614
- Infinity: 11
615
- };
616
- function serializeArray(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
617
- if (parents.has(value)) {
618
- throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
619
-
620
- Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
621
- }
622
- parents.add(value);
623
- const serialized = value.map((v) => {
624
- return convertToSerializedForm(v, metadata, parents);
625
- });
626
- parents.delete(value);
627
- return serialized;
628
- }
629
- function serializeObject(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
630
- if (parents.has(value)) {
631
- throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
632
-
633
- Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
634
- }
635
- parents.add(value);
636
- const serialized = Object.fromEntries(
637
- Object.entries(value).map(([k, v]) => {
638
- return [k, convertToSerializedForm(v, metadata, parents)];
639
- })
640
- );
641
- parents.delete(value);
642
- return serialized;
643
- }
644
- function convertToSerializedForm(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
645
- const tag = Object.prototype.toString.call(value);
646
- switch (tag) {
647
- case "[object Date]": {
648
- return [PROP_TYPE.Date, value.toISOString()];
649
- }
650
- case "[object RegExp]": {
651
- return [PROP_TYPE.RegExp, value.source];
652
- }
653
- case "[object Map]": {
654
- return [PROP_TYPE.Map, serializeArray(Array.from(value), metadata, parents)];
655
- }
656
- case "[object Set]": {
657
- return [PROP_TYPE.Set, serializeArray(Array.from(value), metadata, parents)];
658
- }
659
- case "[object BigInt]": {
660
- return [PROP_TYPE.BigInt, value.toString()];
661
- }
662
- case "[object URL]": {
663
- return [PROP_TYPE.URL, value.toString()];
664
- }
665
- case "[object Array]": {
666
- return [PROP_TYPE.JSON, serializeArray(value, metadata, parents)];
667
- }
668
- case "[object Uint8Array]": {
669
- return [PROP_TYPE.Uint8Array, Array.from(value)];
670
- }
671
- case "[object Uint16Array]": {
672
- return [PROP_TYPE.Uint16Array, Array.from(value)];
673
- }
674
- case "[object Uint32Array]": {
675
- return [PROP_TYPE.Uint32Array, Array.from(value)];
676
- }
677
- default: {
678
- if (value !== null && typeof value === "object") {
679
- return [PROP_TYPE.Value, serializeObject(value, metadata, parents)];
680
- }
681
- if (value === Infinity) {
682
- return [PROP_TYPE.Infinity, 1];
683
- }
684
- if (value === -Infinity) {
685
- return [PROP_TYPE.Infinity, -1];
686
- }
687
- if (value === void 0) {
688
- return [PROP_TYPE.Value];
689
- }
690
- return [PROP_TYPE.Value, value];
691
- }
692
- }
693
- }
694
- function serializeProps(props, metadata) {
695
- const serialized = JSON.stringify(serializeObject(props, metadata));
696
- return serialized;
697
- }
698
-
699
- const transitionDirectivesToCopyOnIsland = Object.freeze([
700
- "data-astro-transition-scope",
701
- "data-astro-transition-persist",
702
- "data-astro-transition-persist-props"
703
- ]);
704
- function extractDirectives(inputProps, clientDirectives) {
705
- let extracted = {
706
- isPage: false,
707
- hydration: null,
708
- props: {},
709
- propsWithoutTransitionAttributes: {}
710
- };
711
- for (const [key, value] of Object.entries(inputProps)) {
712
- if (key.startsWith("server:")) {
713
- if (key === "server:root") {
714
- extracted.isPage = true;
715
- }
716
- }
717
- if (key.startsWith("client:")) {
718
- if (!extracted.hydration) {
719
- extracted.hydration = {
720
- directive: "",
721
- value: "",
722
- componentUrl: "",
723
- componentExport: { value: "" }
724
- };
725
- }
726
- switch (key) {
727
- case "client:component-path": {
728
- extracted.hydration.componentUrl = value;
729
- break;
730
- }
731
- case "client:component-export": {
732
- extracted.hydration.componentExport.value = value;
733
- break;
734
- }
735
- // This is a special prop added to prove that the client hydration method
736
- // was added statically.
737
- case "client:component-hydration": {
738
- break;
739
- }
740
- case "client:display-name": {
741
- break;
742
- }
743
- default: {
744
- extracted.hydration.directive = key.split(":")[1];
745
- extracted.hydration.value = value;
746
- if (!clientDirectives.has(extracted.hydration.directive)) {
747
- const hydrationMethods = Array.from(clientDirectives.keys()).map((d) => `client:${d}`).join(", ");
748
- throw new Error(
749
- `Error: invalid hydration directive "${key}". Supported hydration methods: ${hydrationMethods}`
750
- );
751
- }
752
- if (extracted.hydration.directive === "media" && typeof extracted.hydration.value !== "string") {
753
- throw new AstroError(MissingMediaQueryDirective);
754
- }
755
- break;
756
- }
757
- }
758
- } else {
759
- extracted.props[key] = value;
760
- if (!transitionDirectivesToCopyOnIsland.includes(key)) {
761
- extracted.propsWithoutTransitionAttributes[key] = value;
762
- }
763
- }
764
- }
765
- for (const sym of Object.getOwnPropertySymbols(inputProps)) {
766
- extracted.props[sym] = inputProps[sym];
767
- extracted.propsWithoutTransitionAttributes[sym] = inputProps[sym];
768
- }
769
- return extracted;
770
- }
771
- async function generateHydrateScript(scriptOptions, metadata) {
772
- const { renderer, result, astroId, props, attrs } = scriptOptions;
773
- const { hydrate, componentUrl, componentExport } = metadata;
774
- if (!componentExport.value) {
775
- throw new AstroError({
776
- ...NoMatchingImport,
777
- message: NoMatchingImport.message(metadata.displayName)
778
- });
779
- }
780
- const island = {
781
- children: "",
782
- props: {
783
- // This is for HMR, probably can avoid it in prod
784
- uid: astroId
785
- }
786
- };
787
- if (attrs) {
788
- for (const [key, value] of Object.entries(attrs)) {
789
- island.props[key] = escapeHTML(value);
790
- }
791
- }
792
- island.props["component-url"] = await result.resolve(decodeURI(componentUrl));
793
- if (renderer.clientEntrypoint) {
794
- island.props["component-export"] = componentExport.value;
795
- island.props["renderer-url"] = await result.resolve(
796
- decodeURI(renderer.clientEntrypoint.toString())
797
- );
798
- island.props["props"] = escapeHTML(serializeProps(props, metadata));
799
- }
800
- island.props["ssr"] = "";
801
- island.props["client"] = hydrate;
802
- let beforeHydrationUrl = await result.resolve("astro:scripts/before-hydration.js");
803
- if (beforeHydrationUrl.length) {
804
- island.props["before-hydration-url"] = beforeHydrationUrl;
805
- }
806
- island.props["opts"] = escapeHTML(
807
- JSON.stringify({
808
- name: metadata.displayName,
809
- value: metadata.hydrateArgs || ""
810
- })
811
- );
812
- transitionDirectivesToCopyOnIsland.forEach((name) => {
813
- if (typeof props[name] !== "undefined") {
814
- island.props[name] = props[name];
815
- }
816
- });
817
- return island;
818
- }
819
-
820
- /**
821
- * shortdash - https://github.com/bibig/node-shorthash
822
- *
823
- * @license
824
- *
825
- * (The MIT License)
826
- *
827
- * Copyright (c) 2013 Bibig <bibig@me.com>
828
- *
829
- * Permission is hereby granted, free of charge, to any person
830
- * obtaining a copy of this software and associated documentation
831
- * files (the "Software"), to deal in the Software without
832
- * restriction, including without limitation the rights to use,
833
- * copy, modify, merge, publish, distribute, sublicense, and/or sell
834
- * copies of the Software, and to permit persons to whom the
835
- * Software is furnished to do so, subject to the following
836
- * conditions:
837
- *
838
- * The above copyright notice and this permission notice shall be
839
- * included in all copies or substantial portions of the Software.
840
- *
841
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
842
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
843
- * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
844
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
845
- * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
846
- * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
847
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
848
- * OTHER DEALINGS IN THE SOFTWARE.
849
- */
850
- const dictionary = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY";
851
- const binary = dictionary.length;
852
- function bitwise(str) {
853
- let hash = 0;
854
- if (str.length === 0) return hash;
855
- for (let i = 0; i < str.length; i++) {
856
- const ch = str.charCodeAt(i);
857
- hash = (hash << 5) - hash + ch;
858
- hash = hash & hash;
859
- }
860
- return hash;
861
- }
862
- function shorthash(text) {
863
- let num;
864
- let result = "";
865
- let integer = bitwise(text);
866
- const sign = integer < 0 ? "Z" : "";
867
- integer = Math.abs(integer);
868
- while (integer >= binary) {
869
- num = integer % binary;
870
- integer = Math.floor(integer / binary);
871
- result = dictionary[num] + result;
872
- }
873
- if (integer > 0) {
874
- result = dictionary[integer] + result;
875
- }
876
- return sign + result;
877
- }
878
-
879
- function isAstroComponentFactory(obj) {
880
- return obj == null ? false : obj.isAstroComponentFactory === true;
881
- }
882
- function isAPropagatingComponent(result, factory) {
883
- let hint = factory.propagation || "none";
884
- if (factory.moduleId && result.componentMetadata.has(factory.moduleId) && hint === "none") {
885
- hint = result.componentMetadata.get(factory.moduleId).propagation;
886
- }
887
- return hint === "in-tree" || hint === "self";
888
- }
889
-
890
- const headAndContentSym = Symbol.for("astro.headAndContent");
891
- function isHeadAndContent(obj) {
892
- return typeof obj === "object" && obj !== null && !!obj[headAndContentSym];
893
- }
894
- function createHeadAndContent(head, content) {
895
- return {
896
- [headAndContentSym]: true,
897
- head,
898
- content
899
- };
900
- }
901
-
902
- var astro_island_prebuilt_dev_default = `(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var l=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>y(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[h,e]=t;return h in i?i[h](e):void 0},a=t=>t.map(o),y=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([h,e])=>[h,o(e)]));class f extends HTMLElement{constructor(){super(...arguments);l(this,"Component");l(this,"hydrator");l(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},p=this.querySelectorAll("template[data-astro-template]");for(let r of p){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let u;try{u=this.hasAttribute("props")?y(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",v=this.getAttribute("component-export");throw v&&(s+=\` (export \${v})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}let d,m=this.hydrator(this);d=performance.now(),await m(this.Component,u,n,{client:this.getAttribute("client")}),d&&this.setAttribute("client-render-time",(performance.now()-d).toString()),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});l(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(\`astro:\${c}\`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[p,{default:u}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),d=this.getAttribute("component-export")||"default";if(!d.includes("."))this.Component=p[d];else{this.Component=p;for(let m of d.split("."))this.Component=this.Component[m]}return this.hydrator=u,this.hydrate},e,this)}catch(n){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,n)}}attributeChangedCallback(){this.hydrate()}}l(f,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",f)}})();`;
903
-
904
- var astro_island_prebuilt_default = `(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var d=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>m(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[l,e]=t;return l in i?i[l](e):void 0},a=t=>t.map(o),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([l,e])=>[l,o(e)]));class y extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},h=this.querySelectorAll("template[data-astro-template]");for(let r of h){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let p;try{p=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",v=this.getAttribute("component-export");throw v&&(s+=\` (export \${v})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}let u;await this.hydrator(this)(this.Component,p,n,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});d(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(\`astro:\${c}\`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[h,{default:p}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),u=this.getAttribute("component-export")||"default";if(!u.includes("."))this.Component=h[u];else{this.Component=h;for(let f of u.split("."))this.Component=this.Component[f]}return this.hydrator=p,this.hydrate},e,this)}catch(n){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,n)}}attributeChangedCallback(){this.hydrate()}}d(y,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",y)}})();`;
905
-
906
- const ISLAND_STYLES = `<style>astro-island,astro-slot,astro-static-slot{display:contents}</style>`;
907
- function determineIfNeedsHydrationScript(result) {
908
- if (result._metadata.hasHydrationScript) {
909
- return false;
910
- }
911
- return result._metadata.hasHydrationScript = true;
912
- }
913
- function determinesIfNeedsDirectiveScript(result, directive) {
914
- if (result._metadata.hasDirectives.has(directive)) {
915
- return false;
916
- }
917
- result._metadata.hasDirectives.add(directive);
918
- return true;
919
- }
920
- function getDirectiveScriptText(result, directive) {
921
- const clientDirectives = result.clientDirectives;
922
- const clientDirective = clientDirectives.get(directive);
923
- if (!clientDirective) {
924
- throw new Error(`Unknown directive: ${directive}`);
925
- }
926
- return clientDirective;
927
- }
928
- function getPrescripts(result, type, directive) {
929
- switch (type) {
930
- case "both":
931
- return `${ISLAND_STYLES}<script>${getDirectiveScriptText(result, directive)};${process.env.NODE_ENV === "development" ? astro_island_prebuilt_dev_default : astro_island_prebuilt_default}</script>`;
932
- case "directive":
933
- return `<script>${getDirectiveScriptText(result, directive)}</script>`;
934
- }
935
- return "";
936
- }
937
-
938
- const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
939
- const htmlBooleanAttributes = /^(?:allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|inert|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|selected|itemscope)$/i;
940
- const AMPERSAND_REGEX = /&/g;
941
- const DOUBLE_QUOTE_REGEX = /"/g;
942
- const STATIC_DIRECTIVES = /* @__PURE__ */ new Set(["set:html", "set:text"]);
943
- const toIdent = (k) => k.trim().replace(/(?!^)\b\w|\s+|\W+/g, (match, index) => {
944
- if (/\W/.test(match)) return "";
945
- return index === 0 ? match : match.toUpperCase();
946
- });
947
- const toAttributeString = (value, shouldEscape = true) => shouldEscape ? String(value).replace(AMPERSAND_REGEX, "&#38;").replace(DOUBLE_QUOTE_REGEX, "&#34;") : value;
948
- const kebab = (k) => k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
949
- const toStyleString = (obj) => Object.entries(obj).filter(([_, v]) => typeof v === "string" && v.trim() || typeof v === "number").map(([k, v]) => {
950
- if (k[0] !== "-" && k[1] !== "-") return `${kebab(k)}:${v}`;
951
- return `${k}:${v}`;
952
- }).join(";");
953
- function defineScriptVars(vars) {
954
- let output = "";
955
- for (const [key, value] of Object.entries(vars)) {
956
- output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace(
957
- /<\/script>/g,
958
- "\\x3C/script>"
959
- )};
960
- `;
961
- }
962
- return markHTMLString(output);
963
- }
964
- function formatList(values) {
965
- if (values.length === 1) {
966
- return values[0];
967
- }
968
- return `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`;
969
- }
970
- function addAttribute(value, key, shouldEscape = true) {
971
- if (value == null) {
972
- return "";
973
- }
974
- if (STATIC_DIRECTIVES.has(key)) {
975
- console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute.
976
-
977
- Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`);
978
- return "";
979
- }
980
- if (key === "class:list") {
981
- const listValue = toAttributeString(clsx(value), shouldEscape);
982
- if (listValue === "") {
983
- return "";
984
- }
985
- return markHTMLString(` ${key.slice(0, -5)}="${listValue}"`);
986
- }
987
- if (key === "style" && !(value instanceof HTMLString)) {
988
- if (Array.isArray(value) && value.length === 2) {
989
- return markHTMLString(
990
- ` ${key}="${toAttributeString(`${toStyleString(value[0])};${value[1]}`, shouldEscape)}"`
991
- );
992
- }
993
- if (typeof value === "object") {
994
- return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`);
995
- }
996
- }
997
- if (key === "className") {
998
- return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`);
999
- }
1000
- if (typeof value === "string" && value.includes("&") && isHttpUrl(value)) {
1001
- return markHTMLString(` ${key}="${toAttributeString(value, false)}"`);
1002
- }
1003
- if (htmlBooleanAttributes.test(key)) {
1004
- return markHTMLString(value ? ` ${key}` : "");
1005
- }
1006
- if (value === "") {
1007
- return markHTMLString(` ${key}`);
1008
- }
1009
- return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
1010
- }
1011
- function internalSpreadAttributes(values, shouldEscape = true) {
1012
- let output = "";
1013
- for (const [key, value] of Object.entries(values)) {
1014
- output += addAttribute(value, key, shouldEscape);
1015
- }
1016
- return markHTMLString(output);
1017
- }
1018
- function renderElement$1(name, { props: _props, children = "" }, shouldEscape = true) {
1019
- const { lang: _, "data-astro-id": astroId, "define:vars": defineVars, ...props } = _props;
1020
- if (defineVars) {
1021
- if (name === "style") {
1022
- delete props["is:global"];
1023
- delete props["is:scoped"];
1024
- }
1025
- if (name === "script") {
1026
- delete props.hoist;
1027
- children = defineScriptVars(defineVars) + "\n" + children;
1028
- }
1029
- }
1030
- if ((children == null || children == "") && voidElementNames.test(name)) {
1031
- return `<${name}${internalSpreadAttributes(props, shouldEscape)}>`;
1032
- }
1033
- return `<${name}${internalSpreadAttributes(props, shouldEscape)}>${children}</${name}>`;
1034
- }
1035
- const noop = () => {
1036
- };
1037
- class BufferedRenderer {
1038
- chunks = [];
1039
- renderPromise;
1040
- destination;
1041
- /**
1042
- * Determines whether buffer has been flushed
1043
- * to the final destination.
1044
- */
1045
- flushed = false;
1046
- constructor(destination, renderFunction) {
1047
- this.destination = destination;
1048
- this.renderPromise = renderFunction(this);
1049
- if (isPromise(this.renderPromise)) {
1050
- Promise.resolve(this.renderPromise).catch(noop);
1051
- }
1052
- }
1053
- write(chunk) {
1054
- if (this.flushed) {
1055
- this.destination.write(chunk);
1056
- } else {
1057
- this.chunks.push(chunk);
1058
- }
1059
- }
1060
- flush() {
1061
- if (this.flushed) {
1062
- throw new Error("The render buffer has already been flushed.");
1063
- }
1064
- this.flushed = true;
1065
- for (const chunk of this.chunks) {
1066
- this.destination.write(chunk);
1067
- }
1068
- return this.renderPromise;
1069
- }
1070
- }
1071
- function createBufferedRenderer(destination, renderFunction) {
1072
- return new BufferedRenderer(destination, renderFunction);
1073
- }
1074
- const isNode = typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]";
1075
- const isDeno = typeof Deno !== "undefined";
1076
- function promiseWithResolvers() {
1077
- let resolve, reject;
1078
- const promise = new Promise((_resolve, _reject) => {
1079
- resolve = _resolve;
1080
- reject = _reject;
1081
- });
1082
- return {
1083
- promise,
1084
- resolve,
1085
- reject
1086
- };
1087
- }
1088
- const VALID_PROTOCOLS = ["http:", "https:"];
1089
- function isHttpUrl(url) {
1090
- try {
1091
- const parsedUrl = new URL(url);
1092
- return VALID_PROTOCOLS.includes(parsedUrl.protocol);
1093
- } catch {
1094
- return false;
1095
- }
1096
- }
1097
-
1098
- const uniqueElements = (item, index, all) => {
1099
- const props = JSON.stringify(item.props);
1100
- const children = item.children;
1101
- return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children);
1102
- };
1103
- function renderAllHeadContent(result) {
1104
- result._metadata.hasRenderedHead = true;
1105
- const styles = Array.from(result.styles).filter(uniqueElements).map(
1106
- (style) => style.props.rel === "stylesheet" ? renderElement$1("link", style) : renderElement$1("style", style)
1107
- );
1108
- result.styles.clear();
1109
- const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => {
1110
- if (result.userAssetsBase) {
1111
- script.props.src = (result.base === "/" ? "" : result.base) + result.userAssetsBase + script.props.src;
1112
- }
1113
- return renderElement$1("script", script, false);
1114
- });
1115
- const links = Array.from(result.links).filter(uniqueElements).map((link) => renderElement$1("link", link, false));
1116
- let content = styles.join("\n") + links.join("\n") + scripts.join("\n");
1117
- if (result._metadata.extraHead.length > 0) {
1118
- for (const part of result._metadata.extraHead) {
1119
- content += part;
1120
- }
1121
- }
1122
- return markHTMLString(content);
1123
- }
1124
- function renderHead() {
1125
- return createRenderInstruction({ type: "head" });
1126
- }
1127
- function maybeRenderHead() {
1128
- return createRenderInstruction({ type: "maybe-head" });
1129
- }
1130
-
1131
- const renderTemplateResultSym = Symbol.for("astro.renderTemplateResult");
1132
- class RenderTemplateResult {
1133
- [renderTemplateResultSym] = true;
1134
- htmlParts;
1135
- expressions;
1136
- error;
1137
- constructor(htmlParts, expressions) {
1138
- this.htmlParts = htmlParts;
1139
- this.error = void 0;
1140
- this.expressions = expressions.map((expression) => {
1141
- if (isPromise(expression)) {
1142
- return Promise.resolve(expression).catch((err) => {
1143
- if (!this.error) {
1144
- this.error = err;
1145
- throw err;
1146
- }
1147
- });
1148
- }
1149
- return expression;
1150
- });
1151
- }
1152
- render(destination) {
1153
- const flushers = this.expressions.map((exp) => {
1154
- return createBufferedRenderer(destination, (bufferDestination) => {
1155
- if (exp || exp === 0) {
1156
- return renderChild(bufferDestination, exp);
1157
- }
1158
- });
1159
- });
1160
- let i = 0;
1161
- const iterate = () => {
1162
- while (i < this.htmlParts.length) {
1163
- const html = this.htmlParts[i];
1164
- const flusher = flushers[i];
1165
- i++;
1166
- if (html) {
1167
- destination.write(markHTMLString(html));
1168
- }
1169
- if (flusher) {
1170
- const result = flusher.flush();
1171
- if (isPromise(result)) {
1172
- return result.then(iterate);
1173
- }
1174
- }
1175
- }
1176
- };
1177
- return iterate();
1178
- }
1179
- }
1180
- function isRenderTemplateResult(obj) {
1181
- return typeof obj === "object" && obj !== null && !!obj[renderTemplateResultSym];
1182
- }
1183
- function renderTemplate(htmlParts, ...expressions) {
1184
- return new RenderTemplateResult(htmlParts, expressions);
1185
- }
1186
-
1187
- const slotString = Symbol.for("astro:slot-string");
1188
- class SlotString extends HTMLString {
1189
- instructions;
1190
- [slotString];
1191
- constructor(content, instructions) {
1192
- super(content);
1193
- this.instructions = instructions;
1194
- this[slotString] = true;
1195
- }
1196
- }
1197
- function isSlotString(str) {
1198
- return !!str[slotString];
1199
- }
1200
- function renderSlot(result, slotted, fallback) {
1201
- if (!slotted && fallback) {
1202
- return renderSlot(result, fallback);
1203
- }
1204
- return {
1205
- async render(destination) {
1206
- await renderChild(destination, typeof slotted === "function" ? slotted(result) : slotted);
1207
- }
1208
- };
1209
- }
1210
- async function renderSlotToString(result, slotted, fallback) {
1211
- let content = "";
1212
- let instructions = null;
1213
- const temporaryDestination = {
1214
- write(chunk) {
1215
- if (chunk instanceof SlotString) {
1216
- content += chunk;
1217
- if (chunk.instructions) {
1218
- instructions ??= [];
1219
- instructions.push(...chunk.instructions);
1220
- }
1221
- } else if (chunk instanceof Response) return;
1222
- else if (typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string") {
1223
- if (instructions === null) {
1224
- instructions = [];
1225
- }
1226
- instructions.push(chunk);
1227
- } else {
1228
- content += chunkToString(result, chunk);
1229
- }
1230
- }
1231
- };
1232
- const renderInstance = renderSlot(result, slotted, fallback);
1233
- await renderInstance.render(temporaryDestination);
1234
- return markHTMLString(new SlotString(content, instructions));
1235
- }
1236
- async function renderSlots(result, slots = {}) {
1237
- let slotInstructions = null;
1238
- let children = {};
1239
- if (slots) {
1240
- await Promise.all(
1241
- Object.entries(slots).map(
1242
- ([key, value]) => renderSlotToString(result, value).then((output) => {
1243
- if (output.instructions) {
1244
- if (slotInstructions === null) {
1245
- slotInstructions = [];
1246
- }
1247
- slotInstructions.push(...output.instructions);
1248
- }
1249
- children[key] = output;
1250
- })
1251
- )
1252
- );
1253
- }
1254
- return { slotInstructions, children };
1255
- }
1256
- function createSlotValueFromString(content) {
1257
- return function() {
1258
- return renderTemplate`${unescapeHTML(content)}`;
1259
- };
1260
- }
1261
-
1262
- const Fragment = Symbol.for("astro:fragment");
1263
- const Renderer = Symbol.for("astro:renderer");
1264
- const encoder$1 = new TextEncoder();
1265
- const decoder$1 = new TextDecoder();
1266
- function stringifyChunk(result, chunk) {
1267
- if (isRenderInstruction(chunk)) {
1268
- const instruction = chunk;
1269
- switch (instruction.type) {
1270
- case "directive": {
1271
- const { hydration } = instruction;
1272
- let needsHydrationScript = hydration && determineIfNeedsHydrationScript(result);
1273
- let needsDirectiveScript = hydration && determinesIfNeedsDirectiveScript(result, hydration.directive);
1274
- let prescriptType = needsHydrationScript ? "both" : needsDirectiveScript ? "directive" : null;
1275
- if (prescriptType) {
1276
- let prescripts = getPrescripts(result, prescriptType, hydration.directive);
1277
- return markHTMLString(prescripts);
1278
- } else {
1279
- return "";
1280
- }
1281
- }
1282
- case "head": {
1283
- if (result._metadata.hasRenderedHead || result.partial) {
1284
- return "";
1285
- }
1286
- return renderAllHeadContent(result);
1287
- }
1288
- case "maybe-head": {
1289
- if (result._metadata.hasRenderedHead || result._metadata.headInTree || result.partial) {
1290
- return "";
1291
- }
1292
- return renderAllHeadContent(result);
1293
- }
1294
- case "renderer-hydration-script": {
1295
- const { rendererSpecificHydrationScripts } = result._metadata;
1296
- const { rendererName } = instruction;
1297
- if (!rendererSpecificHydrationScripts.has(rendererName)) {
1298
- rendererSpecificHydrationScripts.add(rendererName);
1299
- return instruction.render();
1300
- }
1301
- return "";
1302
- }
1303
- default: {
1304
- throw new Error(`Unknown chunk type: ${chunk.type}`);
1305
- }
1306
- }
1307
- } else if (chunk instanceof Response) {
1308
- return "";
1309
- } else if (isSlotString(chunk)) {
1310
- let out = "";
1311
- const c = chunk;
1312
- if (c.instructions) {
1313
- for (const instr of c.instructions) {
1314
- out += stringifyChunk(result, instr);
1315
- }
1316
- }
1317
- out += chunk.toString();
1318
- return out;
1319
- }
1320
- return chunk.toString();
1321
- }
1322
- function chunkToString(result, chunk) {
1323
- if (ArrayBuffer.isView(chunk)) {
1324
- return decoder$1.decode(chunk);
1325
- } else {
1326
- return stringifyChunk(result, chunk);
1327
- }
1328
- }
1329
- function chunkToByteArray(result, chunk) {
1330
- if (ArrayBuffer.isView(chunk)) {
1331
- return chunk;
1332
- } else {
1333
- const stringified = stringifyChunk(result, chunk);
1334
- return encoder$1.encode(stringified.toString());
1335
- }
1336
- }
1337
- function isRenderInstance(obj) {
1338
- return !!obj && typeof obj === "object" && "render" in obj && typeof obj.render === "function";
1339
- }
1340
-
1341
- function renderChild(destination, child) {
1342
- if (isPromise(child)) {
1343
- return child.then((x) => renderChild(destination, x));
1344
- }
1345
- if (child instanceof SlotString) {
1346
- destination.write(child);
1347
- return;
1348
- }
1349
- if (isHTMLString(child)) {
1350
- destination.write(child);
1351
- return;
1352
- }
1353
- if (Array.isArray(child)) {
1354
- return renderArray(destination, child);
1355
- }
1356
- if (typeof child === "function") {
1357
- return renderChild(destination, child());
1358
- }
1359
- if (!child && child !== 0) {
1360
- return;
1361
- }
1362
- if (typeof child === "string") {
1363
- destination.write(markHTMLString(escapeHTML(child)));
1364
- return;
1365
- }
1366
- if (isRenderInstance(child)) {
1367
- return child.render(destination);
1368
- }
1369
- if (isRenderTemplateResult(child)) {
1370
- return child.render(destination);
1371
- }
1372
- if (isAstroComponentInstance(child)) {
1373
- return child.render(destination);
1374
- }
1375
- if (ArrayBuffer.isView(child)) {
1376
- destination.write(child);
1377
- return;
1378
- }
1379
- if (typeof child === "object" && (Symbol.asyncIterator in child || Symbol.iterator in child)) {
1380
- if (Symbol.asyncIterator in child) {
1381
- return renderAsyncIterable(destination, child);
1382
- }
1383
- return renderIterable(destination, child);
1384
- }
1385
- destination.write(child);
1386
- }
1387
- function renderArray(destination, children) {
1388
- const flushers = children.map((c) => {
1389
- return createBufferedRenderer(destination, (bufferDestination) => {
1390
- return renderChild(bufferDestination, c);
1391
- });
1392
- });
1393
- const iterator = flushers[Symbol.iterator]();
1394
- const iterate = () => {
1395
- for (; ; ) {
1396
- const { value: flusher, done } = iterator.next();
1397
- if (done) {
1398
- break;
1399
- }
1400
- const result = flusher.flush();
1401
- if (isPromise(result)) {
1402
- return result.then(iterate);
1403
- }
1404
- }
1405
- };
1406
- return iterate();
1407
- }
1408
- function renderIterable(destination, children) {
1409
- const iterator = children[Symbol.iterator]();
1410
- const iterate = () => {
1411
- for (; ; ) {
1412
- const { value, done } = iterator.next();
1413
- if (done) {
1414
- break;
1415
- }
1416
- const result = renderChild(destination, value);
1417
- if (isPromise(result)) {
1418
- return result.then(iterate);
1419
- }
1420
- }
1421
- };
1422
- return iterate();
1423
- }
1424
- async function renderAsyncIterable(destination, children) {
1425
- for await (const value of children) {
1426
- await renderChild(destination, value);
1427
- }
1428
- }
1429
-
1430
- const astroComponentInstanceSym = Symbol.for("astro.componentInstance");
1431
- class AstroComponentInstance {
1432
- [astroComponentInstanceSym] = true;
1433
- result;
1434
- props;
1435
- slotValues;
1436
- factory;
1437
- returnValue;
1438
- constructor(result, props, slots, factory) {
1439
- this.result = result;
1440
- this.props = props;
1441
- this.factory = factory;
1442
- this.slotValues = {};
1443
- for (const name in slots) {
1444
- let didRender = false;
1445
- let value = slots[name](result);
1446
- this.slotValues[name] = () => {
1447
- if (!didRender) {
1448
- didRender = true;
1449
- return value;
1450
- }
1451
- return slots[name](result);
1452
- };
1453
- }
1454
- }
1455
- init(result) {
1456
- if (this.returnValue !== void 0) {
1457
- return this.returnValue;
1458
- }
1459
- this.returnValue = this.factory(result, this.props, this.slotValues);
1460
- if (isPromise(this.returnValue)) {
1461
- this.returnValue.then((resolved) => {
1462
- this.returnValue = resolved;
1463
- }).catch(() => {
1464
- });
1465
- }
1466
- return this.returnValue;
1467
- }
1468
- render(destination) {
1469
- const returnValue = this.init(this.result);
1470
- if (isPromise(returnValue)) {
1471
- return returnValue.then((x) => this.renderImpl(destination, x));
1472
- }
1473
- return this.renderImpl(destination, returnValue);
1474
- }
1475
- renderImpl(destination, returnValue) {
1476
- if (isHeadAndContent(returnValue)) {
1477
- return returnValue.content.render(destination);
1478
- } else {
1479
- return renderChild(destination, returnValue);
1480
- }
1481
- }
1482
- }
1483
- function validateComponentProps(props, displayName) {
1484
- if (props != null) {
1485
- for (const prop of Object.keys(props)) {
1486
- if (prop.startsWith("client:")) {
1487
- console.warn(
1488
- `You are attempting to render <${displayName} ${prop} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`
1489
- );
1490
- }
1491
- }
1492
- }
1493
- }
1494
- function createAstroComponentInstance(result, displayName, factory, props, slots = {}) {
1495
- validateComponentProps(props, displayName);
1496
- const instance = new AstroComponentInstance(result, props, slots, factory);
1497
- if (isAPropagatingComponent(result, factory)) {
1498
- result._metadata.propagators.add(instance);
1499
- }
1500
- return instance;
1501
- }
1502
- function isAstroComponentInstance(obj) {
1503
- return typeof obj === "object" && obj !== null && !!obj[astroComponentInstanceSym];
1504
- }
1505
-
1506
- const DOCTYPE_EXP = /<!doctype html/i;
1507
- async function renderToString(result, componentFactory, props, children, isPage = false, route) {
1508
- const templateResult = await callComponentAsTemplateResultOrResponse(
1509
- result,
1510
- componentFactory,
1511
- props,
1512
- children,
1513
- route
1514
- );
1515
- if (templateResult instanceof Response) return templateResult;
1516
- let str = "";
1517
- let renderedFirstPageChunk = false;
1518
- if (isPage) {
1519
- await bufferHeadContent(result);
1520
- }
1521
- const destination = {
1522
- write(chunk) {
1523
- if (isPage && !renderedFirstPageChunk) {
1524
- renderedFirstPageChunk = true;
1525
- if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
1526
- const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
1527
- str += doctype;
1528
- }
1529
- }
1530
- if (chunk instanceof Response) return;
1531
- str += chunkToString(result, chunk);
1532
- }
1533
- };
1534
- await templateResult.render(destination);
1535
- return str;
1536
- }
1537
- async function renderToReadableStream(result, componentFactory, props, children, isPage = false, route) {
1538
- const templateResult = await callComponentAsTemplateResultOrResponse(
1539
- result,
1540
- componentFactory,
1541
- props,
1542
- children,
1543
- route
1544
- );
1545
- if (templateResult instanceof Response) return templateResult;
1546
- let renderedFirstPageChunk = false;
1547
- if (isPage) {
1548
- await bufferHeadContent(result);
1549
- }
1550
- return new ReadableStream({
1551
- start(controller) {
1552
- const destination = {
1553
- write(chunk) {
1554
- if (isPage && !renderedFirstPageChunk) {
1555
- renderedFirstPageChunk = true;
1556
- if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
1557
- const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
1558
- controller.enqueue(encoder$1.encode(doctype));
1559
- }
1560
- }
1561
- if (chunk instanceof Response) {
1562
- throw new AstroError({
1563
- ...ResponseSentError
1564
- });
1565
- }
1566
- const bytes = chunkToByteArray(result, chunk);
1567
- controller.enqueue(bytes);
1568
- }
1569
- };
1570
- (async () => {
1571
- try {
1572
- await templateResult.render(destination);
1573
- controller.close();
1574
- } catch (e) {
1575
- if (AstroError.is(e) && !e.loc) {
1576
- e.setLocation({
1577
- file: route?.component
1578
- });
1579
- }
1580
- setTimeout(() => controller.error(e), 0);
1581
- }
1582
- })();
1583
- },
1584
- cancel() {
1585
- result.cancelled = true;
1586
- }
1587
- });
1588
- }
1589
- async function callComponentAsTemplateResultOrResponse(result, componentFactory, props, children, route) {
1590
- const factoryResult = await componentFactory(result, props, children);
1591
- if (factoryResult instanceof Response) {
1592
- return factoryResult;
1593
- } else if (isHeadAndContent(factoryResult)) {
1594
- if (!isRenderTemplateResult(factoryResult.content)) {
1595
- throw new AstroError({
1596
- ...OnlyResponseCanBeReturned,
1597
- message: OnlyResponseCanBeReturned.message(
1598
- route?.route,
1599
- typeof factoryResult
1600
- ),
1601
- location: {
1602
- file: route?.component
1603
- }
1604
- });
1605
- }
1606
- return factoryResult.content;
1607
- } else if (!isRenderTemplateResult(factoryResult)) {
1608
- throw new AstroError({
1609
- ...OnlyResponseCanBeReturned,
1610
- message: OnlyResponseCanBeReturned.message(route?.route, typeof factoryResult),
1611
- location: {
1612
- file: route?.component
1613
- }
1614
- });
1615
- }
1616
- return factoryResult;
1617
- }
1618
- async function bufferHeadContent(result) {
1619
- const iterator = result._metadata.propagators.values();
1620
- while (true) {
1621
- const { value, done } = iterator.next();
1622
- if (done) {
1623
- break;
1624
- }
1625
- const returnValue = await value.init(result);
1626
- if (isHeadAndContent(returnValue)) {
1627
- result._metadata.extraHead.push(returnValue.head);
1628
- }
1629
- }
1630
- }
1631
- async function renderToAsyncIterable(result, componentFactory, props, children, isPage = false, route) {
1632
- const templateResult = await callComponentAsTemplateResultOrResponse(
1633
- result,
1634
- componentFactory,
1635
- props,
1636
- children,
1637
- route
1638
- );
1639
- if (templateResult instanceof Response) return templateResult;
1640
- let renderedFirstPageChunk = false;
1641
- if (isPage) {
1642
- await bufferHeadContent(result);
1643
- }
1644
- let error = null;
1645
- let next = null;
1646
- const buffer = [];
1647
- let renderingComplete = false;
1648
- const iterator = {
1649
- async next() {
1650
- if (result.cancelled) return { done: true, value: void 0 };
1651
- if (next !== null) {
1652
- await next.promise;
1653
- } else if (!renderingComplete && !buffer.length) {
1654
- next = promiseWithResolvers();
1655
- await next.promise;
1656
- }
1657
- if (!renderingComplete) {
1658
- next = promiseWithResolvers();
1659
- }
1660
- if (error) {
1661
- throw error;
1662
- }
1663
- let length = 0;
1664
- for (let i = 0, len = buffer.length; i < len; i++) {
1665
- length += buffer[i].length;
1666
- }
1667
- let mergedArray = new Uint8Array(length);
1668
- let offset = 0;
1669
- for (let i = 0, len = buffer.length; i < len; i++) {
1670
- const item = buffer[i];
1671
- mergedArray.set(item, offset);
1672
- offset += item.length;
1673
- }
1674
- buffer.length = 0;
1675
- const returnValue = {
1676
- // The iterator is done when rendering has finished
1677
- // and there are no more chunks to return.
1678
- done: length === 0 && renderingComplete,
1679
- value: mergedArray
1680
- };
1681
- return returnValue;
1682
- },
1683
- async return() {
1684
- result.cancelled = true;
1685
- return { done: true, value: void 0 };
1686
- }
1687
- };
1688
- const destination = {
1689
- write(chunk) {
1690
- if (isPage && !renderedFirstPageChunk) {
1691
- renderedFirstPageChunk = true;
1692
- if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
1693
- const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
1694
- buffer.push(encoder$1.encode(doctype));
1695
- }
1696
- }
1697
- if (chunk instanceof Response) {
1698
- throw new AstroError(ResponseSentError);
1699
- }
1700
- const bytes = chunkToByteArray(result, chunk);
1701
- if (bytes.length > 0) {
1702
- buffer.push(bytes);
1703
- next?.resolve();
1704
- } else if (buffer.length > 0) {
1705
- next?.resolve();
1706
- }
1707
- }
1708
- };
1709
- const renderResult = toPromise(() => templateResult.render(destination));
1710
- renderResult.catch((err) => {
1711
- error = err;
1712
- }).finally(() => {
1713
- renderingComplete = true;
1714
- next?.resolve();
1715
- });
1716
- return {
1717
- [Symbol.asyncIterator]() {
1718
- return iterator;
1719
- }
1720
- };
1721
- }
1722
- function toPromise(fn) {
1723
- try {
1724
- const result = fn();
1725
- return isPromise(result) ? result : Promise.resolve(result);
1726
- } catch (err) {
1727
- return Promise.reject(err);
1728
- }
1729
- }
1730
-
1731
- function componentIsHTMLElement(Component) {
1732
- return typeof HTMLElement !== "undefined" && HTMLElement.isPrototypeOf(Component);
1733
- }
1734
- async function renderHTMLElement(result, constructor, props, slots) {
1735
- const name = getHTMLElementName(constructor);
1736
- let attrHTML = "";
1737
- for (const attr in props) {
1738
- attrHTML += ` ${attr}="${toAttributeString(await props[attr])}"`;
1739
- }
1740
- return markHTMLString(
1741
- `<${name}${attrHTML}>${await renderSlotToString(result, slots?.default)}</${name}>`
1742
- );
1743
- }
1744
- function getHTMLElementName(constructor) {
1745
- const definedName = customElements.getName(constructor);
1746
- if (definedName) return definedName;
1747
- const assignedName = constructor.name.replace(/^HTML|Element$/g, "").replace(/[A-Z]/g, "-$&").toLowerCase().replace(/^-/, "html-");
1748
- return assignedName;
1749
- }
1750
-
1751
- const ALGORITHM = "AES-GCM";
1752
- async function decodeKey(encoded) {
1753
- const bytes = decodeBase64(encoded);
1754
- return crypto.subtle.importKey("raw", bytes, ALGORITHM, true, ["encrypt", "decrypt"]);
1755
- }
1756
- const encoder = new TextEncoder();
1757
- const decoder = new TextDecoder();
1758
- const IV_LENGTH = 24;
1759
- async function encryptString(key, raw) {
1760
- const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH / 2));
1761
- const data = encoder.encode(raw);
1762
- const buffer = await crypto.subtle.encrypt(
1763
- {
1764
- name: ALGORITHM,
1765
- iv
1766
- },
1767
- key,
1768
- data
1769
- );
1770
- return encodeHexUpperCase(iv) + encodeBase64(new Uint8Array(buffer));
1771
- }
1772
- async function decryptString(key, encoded) {
1773
- const iv = decodeHex(encoded.slice(0, IV_LENGTH));
1774
- const dataArray = decodeBase64(encoded.slice(IV_LENGTH));
1775
- const decryptedBuffer = await crypto.subtle.decrypt(
1776
- {
1777
- name: ALGORITHM,
1778
- iv
1779
- },
1780
- key,
1781
- dataArray
1782
- );
1783
- const decryptedString = decoder.decode(decryptedBuffer);
1784
- return decryptedString;
1785
- }
1786
-
1787
- const internalProps = /* @__PURE__ */ new Set([
1788
- "server:component-path",
1789
- "server:component-export",
1790
- "server:component-directive",
1791
- "server:defer"
1792
- ]);
1793
- function containsServerDirective(props) {
1794
- return "server:component-directive" in props;
1795
- }
1796
- const SCRIPT_RE = /<\/script/giu;
1797
- const COMMENT_RE = /<!--/gu;
1798
- const SCRIPT_REPLACER = "<\\/script";
1799
- const COMMENT_REPLACER = "\\u003C!--";
1800
- function safeJsonStringify(obj) {
1801
- return JSON.stringify(obj).replace(SCRIPT_RE, SCRIPT_REPLACER).replace(COMMENT_RE, COMMENT_REPLACER);
1802
- }
1803
- function createSearchParams(componentExport, encryptedProps, slots) {
1804
- const params = new URLSearchParams();
1805
- params.set("e", componentExport);
1806
- params.set("p", encryptedProps);
1807
- params.set("s", slots);
1808
- return params;
1809
- }
1810
- function isWithinURLLimit(pathname, params) {
1811
- const url = pathname + "?" + params.toString();
1812
- const chars = url.length;
1813
- return chars < 2048;
1814
- }
1815
- function renderServerIsland(result, _displayName, props, slots) {
1816
- return {
1817
- async render(destination) {
1818
- const componentPath = props["server:component-path"];
1819
- const componentExport = props["server:component-export"];
1820
- const componentId = result.serverIslandNameMap.get(componentPath);
1821
- if (!componentId) {
1822
- throw new Error(`Could not find server component name`);
1823
- }
1824
- for (const key2 of Object.keys(props)) {
1825
- if (internalProps.has(key2)) {
1826
- delete props[key2];
1827
- }
1828
- }
1829
- destination.write("<!--[if astro]>server-island-start<![endif]-->");
1830
- const renderedSlots = {};
1831
- for (const name in slots) {
1832
- if (name !== "fallback") {
1833
- const content = await renderSlotToString(result, slots[name]);
1834
- renderedSlots[name] = content.toString();
1835
- } else {
1836
- await renderChild(destination, slots.fallback(result));
1837
- }
1838
- }
1839
- const key = await result.key;
1840
- const propsEncrypted = Object.keys(props).length === 0 ? "" : await encryptString(key, JSON.stringify(props));
1841
- const hostId = crypto.randomUUID();
1842
- const slash = result.base.endsWith("/") ? "" : "/";
1843
- let serverIslandUrl = `${result.base}${slash}_server-islands/${componentId}${result.trailingSlash === "always" ? "/" : ""}`;
1844
- const potentialSearchParams = createSearchParams(
1845
- componentExport,
1846
- propsEncrypted,
1847
- safeJsonStringify(renderedSlots)
1848
- );
1849
- const useGETRequest = isWithinURLLimit(serverIslandUrl, potentialSearchParams);
1850
- if (useGETRequest) {
1851
- serverIslandUrl += "?" + potentialSearchParams.toString();
1852
- destination.write(
1853
- `<link rel="preload" as="fetch" href="${serverIslandUrl}" crossorigin="anonymous">`
1854
- );
1855
- }
1856
- destination.write(`<script async type="module" data-island-id="${hostId}">
1857
- let script = document.querySelector('script[data-island-id="${hostId}"]');
1858
-
1859
- ${useGETRequest ? (
1860
- // GET request
1861
- `let response = await fetch('${serverIslandUrl}');
1862
- `
1863
- ) : (
1864
- // POST request
1865
- `let data = {
1866
- componentExport: ${safeJsonStringify(componentExport)},
1867
- encryptedProps: ${safeJsonStringify(propsEncrypted)},
1868
- slots: ${safeJsonStringify(renderedSlots)},
1869
- };
1870
-
1871
- let response = await fetch('${serverIslandUrl}', {
1872
- method: 'POST',
1873
- body: JSON.stringify(data),
1874
- });
1875
- `
1876
- )}
1877
- if (script) {
1878
- if(
1879
- response.status === 200
1880
- && response.headers.has('content-type')
1881
- && response.headers.get('content-type').split(";")[0].trim() === 'text/html') {
1882
- let html = await response.text();
1883
-
1884
- // Swap!
1885
- while(script.previousSibling &&
1886
- script.previousSibling.nodeType !== 8 &&
1887
- script.previousSibling.data !== '[if astro]>server-island-start<![endif]') {
1888
- script.previousSibling.remove();
1889
- }
1890
- script.previousSibling?.remove();
1891
-
1892
- let frag = document.createRange().createContextualFragment(html);
1893
- script.before(frag);
1894
- }
1895
- script.remove();
1896
- }
1897
- </script>`);
1898
- }
1899
- };
1900
- }
1901
-
1902
- const needsHeadRenderingSymbol = Symbol.for("astro.needsHeadRendering");
1903
- const rendererAliases = /* @__PURE__ */ new Map([["solid", "solid-js"]]);
1904
- const clientOnlyValues = /* @__PURE__ */ new Set(["solid-js", "react", "preact", "vue", "svelte"]);
1905
- function guessRenderers(componentUrl) {
1906
- const extname = componentUrl?.split(".").pop();
1907
- switch (extname) {
1908
- case "svelte":
1909
- return ["@astrojs/svelte"];
1910
- case "vue":
1911
- return ["@astrojs/vue"];
1912
- case "jsx":
1913
- case "tsx":
1914
- return ["@astrojs/react", "@astrojs/preact", "@astrojs/solid-js", "@astrojs/vue (jsx)"];
1915
- case void 0:
1916
- default:
1917
- return [
1918
- "@astrojs/react",
1919
- "@astrojs/preact",
1920
- "@astrojs/solid-js",
1921
- "@astrojs/vue",
1922
- "@astrojs/svelte"
1923
- ];
1924
- }
1925
- }
1926
- function isFragmentComponent(Component) {
1927
- return Component === Fragment;
1928
- }
1929
- function isHTMLComponent(Component) {
1930
- return Component && Component["astro:html"] === true;
1931
- }
1932
- const ASTRO_SLOT_EXP = /<\/?astro-slot\b[^>]*>/g;
1933
- const ASTRO_STATIC_SLOT_EXP = /<\/?astro-static-slot\b[^>]*>/g;
1934
- function removeStaticAstroSlot(html, supportsAstroStaticSlot = true) {
1935
- const exp = supportsAstroStaticSlot ? ASTRO_STATIC_SLOT_EXP : ASTRO_SLOT_EXP;
1936
- return html.replace(exp, "");
1937
- }
1938
- async function renderFrameworkComponent(result, displayName, Component, _props, slots = {}) {
1939
- if (!Component && "client:only" in _props === false) {
1940
- throw new Error(
1941
- `Unable to render ${displayName} because it is ${Component}!
1942
- Did you forget to import the component or is it possible there is a typo?`
1943
- );
1944
- }
1945
- const { renderers, clientDirectives } = result;
1946
- const metadata = {
1947
- astroStaticSlot: true,
1948
- displayName
1949
- };
1950
- const { hydration, isPage, props, propsWithoutTransitionAttributes } = extractDirectives(
1951
- _props,
1952
- clientDirectives
1953
- );
1954
- let html = "";
1955
- let attrs = void 0;
1956
- if (hydration) {
1957
- metadata.hydrate = hydration.directive;
1958
- metadata.hydrateArgs = hydration.value;
1959
- metadata.componentExport = hydration.componentExport;
1960
- metadata.componentUrl = hydration.componentUrl;
1961
- }
1962
- const probableRendererNames = guessRenderers(metadata.componentUrl);
1963
- const validRenderers = renderers.filter((r) => r.name !== "astro:jsx");
1964
- const { children, slotInstructions } = await renderSlots(result, slots);
1965
- let renderer;
1966
- if (metadata.hydrate !== "only") {
1967
- let isTagged = false;
1968
- try {
1969
- isTagged = Component && Component[Renderer];
1970
- } catch {
1971
- }
1972
- if (isTagged) {
1973
- const rendererName = Component[Renderer];
1974
- renderer = renderers.find(({ name }) => name === rendererName);
1975
- }
1976
- if (!renderer) {
1977
- let error;
1978
- for (const r of renderers) {
1979
- try {
1980
- if (await r.ssr.check.call({ result }, Component, props, children)) {
1981
- renderer = r;
1982
- break;
1983
- }
1984
- } catch (e) {
1985
- error ??= e;
1986
- }
1987
- }
1988
- if (!renderer && error) {
1989
- throw error;
1990
- }
1991
- }
1992
- if (!renderer && typeof HTMLElement === "function" && componentIsHTMLElement(Component)) {
1993
- const output = await renderHTMLElement(
1994
- result,
1995
- Component,
1996
- _props,
1997
- slots
1998
- );
1999
- return {
2000
- render(destination) {
2001
- destination.write(output);
2002
- }
2003
- };
2004
- }
2005
- } else {
2006
- if (metadata.hydrateArgs) {
2007
- const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs;
2008
- if (clientOnlyValues.has(rendererName)) {
2009
- renderer = renderers.find(
2010
- ({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
2011
- );
2012
- }
2013
- }
2014
- if (!renderer && validRenderers.length === 1) {
2015
- renderer = validRenderers[0];
2016
- }
2017
- if (!renderer) {
2018
- const extname = metadata.componentUrl?.split(".").pop();
2019
- renderer = renderers.find(({ name }) => name === `@astrojs/${extname}` || name === extname);
2020
- }
2021
- }
2022
- let componentServerRenderEndTime;
2023
- if (!renderer) {
2024
- if (metadata.hydrate === "only") {
2025
- const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs;
2026
- if (clientOnlyValues.has(rendererName)) {
2027
- const plural = validRenderers.length > 1;
2028
- throw new AstroError({
2029
- ...NoMatchingRenderer,
2030
- message: NoMatchingRenderer.message(
2031
- metadata.displayName,
2032
- metadata?.componentUrl?.split(".").pop(),
2033
- plural,
2034
- validRenderers.length
2035
- ),
2036
- hint: NoMatchingRenderer.hint(
2037
- formatList(probableRendererNames.map((r) => "`" + r + "`"))
2038
- )
2039
- });
2040
- } else {
2041
- throw new AstroError({
2042
- ...NoClientOnlyHint,
2043
- message: NoClientOnlyHint.message(metadata.displayName),
2044
- hint: NoClientOnlyHint.hint(
2045
- probableRendererNames.map((r) => r.replace("@astrojs/", "")).join("|")
2046
- )
2047
- });
2048
- }
2049
- } else if (typeof Component !== "string") {
2050
- const matchingRenderers = validRenderers.filter(
2051
- (r) => probableRendererNames.includes(r.name)
2052
- );
2053
- const plural = validRenderers.length > 1;
2054
- if (matchingRenderers.length === 0) {
2055
- throw new AstroError({
2056
- ...NoMatchingRenderer,
2057
- message: NoMatchingRenderer.message(
2058
- metadata.displayName,
2059
- metadata?.componentUrl?.split(".").pop(),
2060
- plural,
2061
- validRenderers.length
2062
- ),
2063
- hint: NoMatchingRenderer.hint(
2064
- formatList(probableRendererNames.map((r) => "`" + r + "`"))
2065
- )
2066
- });
2067
- } else if (matchingRenderers.length === 1) {
2068
- renderer = matchingRenderers[0];
2069
- ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
2070
- { result },
2071
- Component,
2072
- propsWithoutTransitionAttributes,
2073
- children,
2074
- metadata
2075
- ));
2076
- } else {
2077
- throw new Error(`Unable to render ${metadata.displayName}!
2078
-
2079
- This component likely uses ${formatList(probableRendererNames)},
2080
- but Astro encountered an error during server-side rendering.
2081
-
2082
- Please ensure that ${metadata.displayName}:
2083
- 1. Does not unconditionally access browser-specific globals like \`window\` or \`document\`.
2084
- If this is unavoidable, use the \`client:only\` hydration directive.
2085
- 2. Does not conditionally return \`null\` or \`undefined\` when rendered on the server.
2086
-
2087
- If you're still stuck, please open an issue on GitHub or join us at https://astro.build/chat.`);
2088
- }
2089
- }
2090
- } else {
2091
- if (metadata.hydrate === "only") {
2092
- html = await renderSlotToString(result, slots?.fallback);
2093
- } else {
2094
- const componentRenderStartTime = performance.now();
2095
- ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
2096
- { result },
2097
- Component,
2098
- propsWithoutTransitionAttributes,
2099
- children,
2100
- metadata
2101
- ));
2102
- if (process.env.NODE_ENV === "development")
2103
- componentServerRenderEndTime = performance.now() - componentRenderStartTime;
2104
- }
2105
- }
2106
- if (!html && typeof Component === "string") {
2107
- const Tag = sanitizeElementName(Component);
2108
- const childSlots = Object.values(children).join("");
2109
- const renderTemplateResult = renderTemplate`<${Tag}${internalSpreadAttributes(
2110
- props
2111
- )}${markHTMLString(
2112
- childSlots === "" && voidElementNames.test(Tag) ? `/>` : `>${childSlots}</${Tag}>`
2113
- )}`;
2114
- html = "";
2115
- const destination = {
2116
- write(chunk) {
2117
- if (chunk instanceof Response) return;
2118
- html += chunkToString(result, chunk);
2119
- }
2120
- };
2121
- await renderTemplateResult.render(destination);
2122
- }
2123
- if (!hydration) {
2124
- return {
2125
- render(destination) {
2126
- if (slotInstructions) {
2127
- for (const instruction of slotInstructions) {
2128
- destination.write(instruction);
2129
- }
2130
- }
2131
- if (isPage || renderer?.name === "astro:jsx") {
2132
- destination.write(html);
2133
- } else if (html && html.length > 0) {
2134
- destination.write(
2135
- markHTMLString(removeStaticAstroSlot(html, renderer?.ssr?.supportsAstroStaticSlot))
2136
- );
2137
- }
2138
- }
2139
- };
2140
- }
2141
- const astroId = shorthash(
2142
- `<!--${metadata.componentExport.value}:${metadata.componentUrl}-->
2143
- ${html}
2144
- ${serializeProps(
2145
- props,
2146
- metadata
2147
- )}`
2148
- );
2149
- const island = await generateHydrateScript(
2150
- { renderer, result, astroId, props, attrs },
2151
- metadata
2152
- );
2153
- if (componentServerRenderEndTime && process.env.NODE_ENV === "development")
2154
- island.props["server-render-time"] = componentServerRenderEndTime;
2155
- let unrenderedSlots = [];
2156
- if (html) {
2157
- if (Object.keys(children).length > 0) {
2158
- for (const key of Object.keys(children)) {
2159
- let tagName = renderer?.ssr?.supportsAstroStaticSlot ? !!metadata.hydrate ? "astro-slot" : "astro-static-slot" : "astro-slot";
2160
- let expectedHTML = key === "default" ? `<${tagName}>` : `<${tagName} name="${key}">`;
2161
- if (!html.includes(expectedHTML)) {
2162
- unrenderedSlots.push(key);
2163
- }
2164
- }
2165
- }
2166
- } else {
2167
- unrenderedSlots = Object.keys(children);
2168
- }
2169
- const template = unrenderedSlots.length > 0 ? unrenderedSlots.map(
2170
- (key) => `<template data-astro-template${key !== "default" ? `="${key}"` : ""}>${children[key]}</template>`
2171
- ).join("") : "";
2172
- island.children = `${html ?? ""}${template}`;
2173
- if (island.children) {
2174
- island.props["await-children"] = "";
2175
- island.children += `<!--astro:end-->`;
2176
- }
2177
- return {
2178
- render(destination) {
2179
- if (slotInstructions) {
2180
- for (const instruction of slotInstructions) {
2181
- destination.write(instruction);
2182
- }
2183
- }
2184
- destination.write(createRenderInstruction({ type: "directive", hydration }));
2185
- if (hydration.directive !== "only" && renderer?.ssr.renderHydrationScript) {
2186
- destination.write(
2187
- createRenderInstruction({
2188
- type: "renderer-hydration-script",
2189
- rendererName: renderer.name,
2190
- render: renderer.ssr.renderHydrationScript
2191
- })
2192
- );
2193
- }
2194
- const renderedElement = renderElement$1("astro-island", island, false);
2195
- destination.write(markHTMLString(renderedElement));
2196
- }
2197
- };
2198
- }
2199
- function sanitizeElementName(tag) {
2200
- const unsafe = /[&<>'"\s]+/;
2201
- if (!unsafe.test(tag)) return tag;
2202
- return tag.trim().split(unsafe)[0].trim();
2203
- }
2204
- async function renderFragmentComponent(result, slots = {}) {
2205
- const children = await renderSlotToString(result, slots?.default);
2206
- return {
2207
- render(destination) {
2208
- if (children == null) return;
2209
- destination.write(children);
2210
- }
2211
- };
2212
- }
2213
- async function renderHTMLComponent(result, Component, _props, slots = {}) {
2214
- const { slotInstructions, children } = await renderSlots(result, slots);
2215
- const html = Component({ slots: children });
2216
- const hydrationHtml = slotInstructions ? slotInstructions.map((instr) => chunkToString(result, instr)).join("") : "";
2217
- return {
2218
- render(destination) {
2219
- destination.write(markHTMLString(hydrationHtml + html));
2220
- }
2221
- };
2222
- }
2223
- function renderAstroComponent(result, displayName, Component, props, slots = {}) {
2224
- if (containsServerDirective(props)) {
2225
- return renderServerIsland(result, displayName, props, slots);
2226
- }
2227
- const instance = createAstroComponentInstance(result, displayName, Component, props, slots);
2228
- return {
2229
- render(destination) {
2230
- return instance.render(destination);
2231
- }
2232
- };
2233
- }
2234
- function renderComponent(result, displayName, Component, props, slots = {}) {
2235
- if (isPromise(Component)) {
2236
- return Component.catch(handleCancellation).then((x) => {
2237
- return renderComponent(result, displayName, x, props, slots);
2238
- });
2239
- }
2240
- if (isFragmentComponent(Component)) {
2241
- return renderFragmentComponent(result, slots).catch(handleCancellation);
2242
- }
2243
- props = normalizeProps(props);
2244
- if (isHTMLComponent(Component)) {
2245
- return renderHTMLComponent(result, Component, props, slots).catch(handleCancellation);
2246
- }
2247
- if (isAstroComponentFactory(Component)) {
2248
- return renderAstroComponent(result, displayName, Component, props, slots);
2249
- }
2250
- return renderFrameworkComponent(result, displayName, Component, props, slots).catch(
2251
- handleCancellation
2252
- );
2253
- function handleCancellation(e) {
2254
- if (result.cancelled)
2255
- return {
2256
- render() {
2257
- }
2258
- };
2259
- throw e;
2260
- }
2261
- }
2262
- function normalizeProps(props) {
2263
- if (props["class:list"] !== void 0) {
2264
- const value = props["class:list"];
2265
- delete props["class:list"];
2266
- props["class"] = clsx(props["class"], value);
2267
- if (props["class"] === "") {
2268
- delete props["class"];
2269
- }
2270
- }
2271
- return props;
2272
- }
2273
- async function renderComponentToString(result, displayName, Component, props, slots = {}, isPage = false, route) {
2274
- let str = "";
2275
- let renderedFirstPageChunk = false;
2276
- let head = "";
2277
- if (isPage && !result.partial && nonAstroPageNeedsHeadInjection(Component)) {
2278
- head += chunkToString(result, maybeRenderHead());
2279
- }
2280
- try {
2281
- const destination = {
2282
- write(chunk) {
2283
- if (isPage && !result.partial && !renderedFirstPageChunk) {
2284
- renderedFirstPageChunk = true;
2285
- if (!/<!doctype html/i.test(String(chunk))) {
2286
- const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
2287
- str += doctype + head;
2288
- }
2289
- }
2290
- if (chunk instanceof Response) return;
2291
- str += chunkToString(result, chunk);
2292
- }
2293
- };
2294
- const renderInstance = await renderComponent(result, displayName, Component, props, slots);
2295
- await renderInstance.render(destination);
2296
- } catch (e) {
2297
- if (AstroError.is(e) && !e.loc) {
2298
- e.setLocation({
2299
- file: route?.component
2300
- });
2301
- }
2302
- throw e;
2303
- }
2304
- return str;
2305
- }
2306
- function nonAstroPageNeedsHeadInjection(pageComponent) {
2307
- return !!pageComponent?.[needsHeadRenderingSymbol];
2308
- }
2309
-
2310
- const ClientOnlyPlaceholder = "astro-client-only";
2311
- const hasTriedRenderComponentSymbol = Symbol("hasTriedRenderComponent");
2312
- async function renderJSX(result, vnode) {
2313
- switch (true) {
2314
- case vnode instanceof HTMLString:
2315
- if (vnode.toString().trim() === "") {
2316
- return "";
2317
- }
2318
- return vnode;
2319
- case typeof vnode === "string":
2320
- return markHTMLString(escapeHTML(vnode));
2321
- case typeof vnode === "function":
2322
- return vnode;
2323
- case (!vnode && vnode !== 0):
2324
- return "";
2325
- case Array.isArray(vnode):
2326
- return markHTMLString(
2327
- (await Promise.all(vnode.map((v) => renderJSX(result, v)))).join("")
2328
- );
2329
- }
2330
- return renderJSXVNode(result, vnode);
2331
- }
2332
- async function renderJSXVNode(result, vnode) {
2333
- if (isVNode(vnode)) {
2334
- switch (true) {
2335
- case !vnode.type: {
2336
- throw new Error(`Unable to render ${result.pathname} because it contains an undefined Component!
2337
- Did you forget to import the component or is it possible there is a typo?`);
2338
- }
2339
- case vnode.type === Symbol.for("astro:fragment"):
2340
- return renderJSX(result, vnode.props.children);
2341
- case vnode.type.isAstroComponentFactory: {
2342
- let props = {};
2343
- let slots = {};
2344
- for (const [key, value] of Object.entries(vnode.props ?? {})) {
2345
- if (key === "children" || value && typeof value === "object" && value["$$slot"]) {
2346
- slots[key === "children" ? "default" : key] = () => renderJSX(result, value);
2347
- } else {
2348
- props[key] = value;
2349
- }
2350
- }
2351
- const str = await renderToString(result, vnode.type, props, slots);
2352
- if (str instanceof Response) {
2353
- throw str;
2354
- }
2355
- const html = markHTMLString(str);
2356
- return html;
2357
- }
2358
- case (!vnode.type && vnode.type !== 0):
2359
- return "";
2360
- case (typeof vnode.type === "string" && vnode.type !== ClientOnlyPlaceholder):
2361
- return markHTMLString(await renderElement(result, vnode.type, vnode.props ?? {}));
2362
- }
2363
- if (vnode.type) {
2364
- let extractSlots2 = function(child) {
2365
- if (Array.isArray(child)) {
2366
- return child.map((c) => extractSlots2(c));
2367
- }
2368
- if (!isVNode(child)) {
2369
- _slots.default.push(child);
2370
- return;
2371
- }
2372
- if ("slot" in child.props) {
2373
- _slots[child.props.slot] = [..._slots[child.props.slot] ?? [], child];
2374
- delete child.props.slot;
2375
- return;
2376
- }
2377
- _slots.default.push(child);
2378
- };
2379
- if (typeof vnode.type === "function" && vnode.props["server:root"]) {
2380
- const output2 = await vnode.type(vnode.props ?? {});
2381
- return await renderJSX(result, output2);
2382
- }
2383
- if (typeof vnode.type === "function") {
2384
- if (vnode.props[hasTriedRenderComponentSymbol]) {
2385
- delete vnode.props[hasTriedRenderComponentSymbol];
2386
- const output2 = await vnode.type(vnode.props ?? {});
2387
- if (output2?.[AstroJSX] || !output2) {
2388
- return await renderJSXVNode(result, output2);
2389
- } else {
2390
- return;
2391
- }
2392
- } else {
2393
- vnode.props[hasTriedRenderComponentSymbol] = true;
2394
- }
2395
- }
2396
- const { children = null, ...props } = vnode.props ?? {};
2397
- const _slots = {
2398
- default: []
2399
- };
2400
- extractSlots2(children);
2401
- for (const [key, value] of Object.entries(props)) {
2402
- if (value?.["$$slot"]) {
2403
- _slots[key] = value;
2404
- delete props[key];
2405
- }
2406
- }
2407
- const slotPromises = [];
2408
- const slots = {};
2409
- for (const [key, value] of Object.entries(_slots)) {
2410
- slotPromises.push(
2411
- renderJSX(result, value).then((output2) => {
2412
- if (output2.toString().trim().length === 0) return;
2413
- slots[key] = () => output2;
2414
- })
2415
- );
2416
- }
2417
- await Promise.all(slotPromises);
2418
- let output;
2419
- if (vnode.type === ClientOnlyPlaceholder && vnode.props["client:only"]) {
2420
- output = await renderComponentToString(
2421
- result,
2422
- vnode.props["client:display-name"] ?? "",
2423
- null,
2424
- props,
2425
- slots
2426
- );
2427
- } else {
2428
- output = await renderComponentToString(
2429
- result,
2430
- typeof vnode.type === "function" ? vnode.type.name : vnode.type,
2431
- vnode.type,
2432
- props,
2433
- slots
2434
- );
2435
- }
2436
- return markHTMLString(output);
2437
- }
2438
- }
2439
- return markHTMLString(`${vnode}`);
2440
- }
2441
- async function renderElement(result, tag, { children, ...props }) {
2442
- return markHTMLString(
2443
- `<${tag}${spreadAttributes(props)}${markHTMLString(
2444
- (children == null || children == "") && voidElementNames.test(tag) ? `/>` : `>${children == null ? "" : await renderJSX(result, prerenderElementChildren(tag, children))}</${tag}>`
2445
- )}`
2446
- );
2447
- }
2448
- function prerenderElementChildren(tag, children) {
2449
- if (typeof children === "string" && (tag === "style" || tag === "script")) {
2450
- return markHTMLString(children);
2451
- } else {
2452
- return children;
2453
- }
2454
- }
2455
-
2456
- async function renderScript(result, id) {
2457
- if (result._metadata.renderedScripts.has(id)) return;
2458
- result._metadata.renderedScripts.add(id);
2459
- const inlined = result.inlinedScripts.get(id);
2460
- if (inlined != null) {
2461
- if (inlined) {
2462
- return markHTMLString(`<script type="module">${inlined}</script>`);
2463
- } else {
2464
- return "";
2465
- }
2466
- }
2467
- const resolved = await result.resolve(id);
2468
- return markHTMLString(
2469
- `<script type="module" src="${result.userAssetsBase ? (result.base === "/" ? "" : result.base) + result.userAssetsBase : ""}${resolved}"></script>`
2470
- );
2471
- }
2472
-
2473
- async function renderPage(result, componentFactory, props, children, streaming, route) {
2474
- if (!isAstroComponentFactory(componentFactory)) {
2475
- result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
2476
- const pageProps = { ...props ?? {}, "server:root": true };
2477
- const str = await renderComponentToString(
2478
- result,
2479
- componentFactory.name,
2480
- componentFactory,
2481
- pageProps,
2482
- {},
2483
- true,
2484
- route
2485
- );
2486
- const bytes = encoder$1.encode(str);
2487
- return new Response(bytes, {
2488
- headers: new Headers([
2489
- ["Content-Type", "text/html"],
2490
- ["Content-Length", bytes.byteLength.toString()]
2491
- ])
2492
- });
2493
- }
2494
- result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
2495
- let body;
2496
- if (streaming) {
2497
- if (isNode && !isDeno) {
2498
- const nodeBody = await renderToAsyncIterable(
2499
- result,
2500
- componentFactory,
2501
- props,
2502
- children,
2503
- true,
2504
- route
2505
- );
2506
- body = nodeBody;
2507
- } else {
2508
- body = await renderToReadableStream(result, componentFactory, props, children, true, route);
2509
- }
2510
- } else {
2511
- body = await renderToString(result, componentFactory, props, children, true, route);
2512
- }
2513
- if (body instanceof Response) return body;
2514
- const init = result.response;
2515
- const headers = new Headers(init.headers);
2516
- if (!streaming && typeof body === "string") {
2517
- body = encoder$1.encode(body);
2518
- headers.set("Content-Length", body.byteLength.toString());
2519
- }
2520
- let status = init.status;
2521
- if (route?.route === "/404") {
2522
- status = 404;
2523
- } else if (route?.route === "/500") {
2524
- status = 500;
2525
- }
2526
- if (status) {
2527
- return new Response(body, { ...init, headers, status });
2528
- } else {
2529
- return new Response(body, { ...init, headers });
2530
- }
2531
- }
2532
-
2533
- function renderScriptElement({ props, children }) {
2534
- return renderElement$1("script", {
2535
- props,
2536
- children
2537
- });
2538
- }
2539
- function renderUniqueStylesheet(result, sheet) {
2540
- if (sheet.type === "external") {
2541
- if (Array.from(result.styles).some((s) => s.props.href === sheet.src)) return "";
2542
- return renderElement$1("link", { props: { rel: "stylesheet", href: sheet.src }, children: "" });
2543
- }
2544
- if (sheet.type === "inline") {
2545
- if (Array.from(result.styles).some((s) => s.children.includes(sheet.content))) return "";
2546
- return renderElement$1("style", { props: {}, children: sheet.content });
2547
- }
2548
- }
2549
-
2550
- const EASE_IN_OUT_QUART = "cubic-bezier(0.76, 0, 0.24, 1)";
2551
- function slide({
2552
- duration
2553
- } = {}) {
2554
- return {
2555
- forwards: {
2556
- old: [
2557
- {
2558
- name: "astroFadeOut",
2559
- duration: duration ?? "90ms",
2560
- easing: EASE_IN_OUT_QUART,
2561
- fillMode: "both"
2562
- },
2563
- {
2564
- name: "astroSlideToLeft",
2565
- duration: duration ?? "220ms",
2566
- easing: EASE_IN_OUT_QUART,
2567
- fillMode: "both"
2568
- }
2569
- ],
2570
- new: [
2571
- {
2572
- name: "astroFadeIn",
2573
- duration: duration ?? "210ms",
2574
- easing: EASE_IN_OUT_QUART,
2575
- delay: duration ? void 0 : "30ms",
2576
- fillMode: "both"
2577
- },
2578
- {
2579
- name: "astroSlideFromRight",
2580
- duration: duration ?? "220ms",
2581
- easing: EASE_IN_OUT_QUART,
2582
- fillMode: "both"
2583
- }
2584
- ]
2585
- },
2586
- backwards: {
2587
- old: [{ name: "astroFadeOut" }, { name: "astroSlideToRight" }],
2588
- new: [{ name: "astroFadeIn" }, { name: "astroSlideFromLeft" }]
2589
- }
2590
- };
2591
- }
2592
- function fade({
2593
- duration
2594
- } = {}) {
2595
- const anim = {
2596
- old: {
2597
- name: "astroFadeOut",
2598
- duration: duration ?? 180,
2599
- easing: EASE_IN_OUT_QUART,
2600
- fillMode: "both"
2601
- },
2602
- new: {
2603
- name: "astroFadeIn",
2604
- duration: duration ?? 180,
2605
- easing: EASE_IN_OUT_QUART,
2606
- fillMode: "both"
2607
- }
2608
- };
2609
- return {
2610
- forwards: anim,
2611
- backwards: anim
2612
- };
2613
- }
2614
-
2615
- const transitionNameMap = /* @__PURE__ */ new WeakMap();
2616
- function incrementTransitionNumber(result) {
2617
- let num = 1;
2618
- if (transitionNameMap.has(result)) {
2619
- num = transitionNameMap.get(result) + 1;
2620
- }
2621
- transitionNameMap.set(result, num);
2622
- return num;
2623
- }
2624
- function createTransitionScope(result, hash) {
2625
- const num = incrementTransitionNumber(result);
2626
- return `astro-${hash}-${num}`;
2627
- }
2628
- const getAnimations = (name) => {
2629
- if (name === "fade") return fade();
2630
- if (name === "slide") return slide();
2631
- if (typeof name === "object") return name;
2632
- };
2633
- const addPairs = (animations, stylesheet) => {
2634
- for (const [direction, images] of Object.entries(animations)) {
2635
- for (const [image, rules] of Object.entries(images)) {
2636
- stylesheet.addAnimationPair(direction, image, rules);
2637
- }
2638
- }
2639
- };
2640
- "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
2641
- "-0123456789_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
2642
- function renderTransition(result, hash, animationName, transitionName) {
2643
- if (!animationName) animationName = "fade";
2644
- const scope = createTransitionScope(result, hash);
2645
- const name = scope;
2646
- const sheet = new ViewTransitionStyleSheet(scope, name);
2647
- const animations = getAnimations(animationName);
2648
- if (animations) {
2649
- addPairs(animations, sheet);
2650
- } else if (animationName === "none") {
2651
- sheet.addFallback("old", "animation: none; mix-blend-mode: normal;");
2652
- sheet.addModern("old", "animation: none; opacity: 0; mix-blend-mode: normal;");
2653
- sheet.addAnimationRaw("new", "animation: none; mix-blend-mode: normal;");
2654
- sheet.addModern("group", "animation: none");
2655
- }
2656
- result._metadata.extraHead.push(markHTMLString(`<style>${sheet.toString()}</style>`));
2657
- return scope;
2658
- }
2659
- class ViewTransitionStyleSheet {
2660
- constructor(scope, name) {
2661
- this.scope = scope;
2662
- this.name = name;
2663
- }
2664
- modern = [];
2665
- fallback = [];
2666
- toString() {
2667
- const { scope, name } = this;
2668
- const [modern, fallback] = [this.modern, this.fallback].map((rules) => rules.join(""));
2669
- return [
2670
- `[data-astro-transition-scope="${scope}"] { view-transition-name: ${name}; }`,
2671
- this.layer(modern),
2672
- fallback
2673
- ].join("");
2674
- }
2675
- layer(cssText) {
2676
- return cssText ? `@layer astro { ${cssText} }` : "";
2677
- }
2678
- addRule(target, cssText) {
2679
- this[target].push(cssText);
2680
- }
2681
- addAnimationRaw(image, animation) {
2682
- this.addModern(image, animation);
2683
- this.addFallback(image, animation);
2684
- }
2685
- addModern(image, animation) {
2686
- const { name } = this;
2687
- this.addRule("modern", `::view-transition-${image}(${name}) { ${animation} }`);
2688
- }
2689
- addFallback(image, animation) {
2690
- const { scope } = this;
2691
- this.addRule(
2692
- "fallback",
2693
- // Two selectors here, the second in case there is an animation on the root.
2694
- `[data-astro-transition-fallback="${image}"] [data-astro-transition-scope="${scope}"],
2695
- [data-astro-transition-fallback="${image}"][data-astro-transition-scope="${scope}"] { ${animation} }`
2696
- );
2697
- }
2698
- addAnimationPair(direction, image, rules) {
2699
- const { scope, name } = this;
2700
- const animation = stringifyAnimation(rules);
2701
- const prefix = direction === "backwards" ? `[data-astro-transition=back]` : direction === "forwards" ? "" : `[data-astro-transition=${direction}]`;
2702
- this.addRule("modern", `${prefix}::view-transition-${image}(${name}) { ${animation} }`);
2703
- this.addRule(
2704
- "fallback",
2705
- `${prefix}[data-astro-transition-fallback="${image}"] [data-astro-transition-scope="${scope}"],
2706
- ${prefix}[data-astro-transition-fallback="${image}"][data-astro-transition-scope="${scope}"] { ${animation} }`
2707
- );
2708
- }
2709
- }
2710
- function addAnimationProperty(builder, prop, value) {
2711
- let arr = builder[prop];
2712
- if (Array.isArray(arr)) {
2713
- arr.push(value.toString());
2714
- } else {
2715
- builder[prop] = [value.toString()];
2716
- }
2717
- }
2718
- function animationBuilder() {
2719
- return {
2720
- toString() {
2721
- let out = "";
2722
- for (let k in this) {
2723
- let value = this[k];
2724
- if (Array.isArray(value)) {
2725
- out += `
2726
- ${k}: ${value.join(", ")};`;
2727
- }
2728
- }
2729
- return out;
2730
- }
2731
- };
2732
- }
2733
- function stringifyAnimation(anim) {
2734
- if (Array.isArray(anim)) {
2735
- return stringifyAnimations(anim);
2736
- } else {
2737
- return stringifyAnimations([anim]);
2738
- }
2739
- }
2740
- function stringifyAnimations(anims) {
2741
- const builder = animationBuilder();
2742
- for (const anim of anims) {
2743
- if (anim.duration) {
2744
- addAnimationProperty(builder, "animation-duration", toTimeValue(anim.duration));
2745
- }
2746
- if (anim.easing) {
2747
- addAnimationProperty(builder, "animation-timing-function", anim.easing);
2748
- }
2749
- if (anim.direction) {
2750
- addAnimationProperty(builder, "animation-direction", anim.direction);
2751
- }
2752
- if (anim.delay) {
2753
- addAnimationProperty(builder, "animation-delay", anim.delay);
2754
- }
2755
- if (anim.fillMode) {
2756
- addAnimationProperty(builder, "animation-fill-mode", anim.fillMode);
2757
- }
2758
- addAnimationProperty(builder, "animation-name", anim.name);
2759
- }
2760
- return builder.toString();
2761
- }
2762
- function toTimeValue(num) {
2763
- return typeof num === "number" ? num + "ms" : num;
2764
- }
2765
-
2766
- function __astro_tag_component__(Component, rendererName) {
2767
- if (!Component) return;
2768
- if (typeof Component !== "function") return;
2769
- Object.defineProperty(Component, Renderer, {
2770
- value: rendererName,
2771
- enumerable: false,
2772
- writable: false
2773
- });
2774
- }
2775
- function spreadAttributes(values = {}, _name, { class: scopedClassName } = {}) {
2776
- let output = "";
2777
- if (scopedClassName) {
2778
- if (typeof values.class !== "undefined") {
2779
- values.class += ` ${scopedClassName}`;
2780
- } else if (typeof values["class:list"] !== "undefined") {
2781
- values["class:list"] = [values["class:list"], scopedClassName];
2782
- } else {
2783
- values.class = scopedClassName;
2784
- }
2785
- }
2786
- for (const [key, value] of Object.entries(values)) {
2787
- output += addAttribute(value, key, true);
2788
- }
2789
- return markHTMLString(output);
2790
- }
2791
-
2792
- const AstroJSX = "astro:jsx";
2793
- const Empty = Symbol("empty");
2794
- const toSlotName = (slotAttr) => slotAttr;
2795
- function isVNode(vnode) {
2796
- return vnode && typeof vnode === "object" && vnode[AstroJSX];
2797
- }
2798
- function transformSlots(vnode) {
2799
- if (typeof vnode.type === "string") return vnode;
2800
- const slots = {};
2801
- if (isVNode(vnode.props.children)) {
2802
- const child = vnode.props.children;
2803
- if (!isVNode(child)) return;
2804
- if (!("slot" in child.props)) return;
2805
- const name = toSlotName(child.props.slot);
2806
- slots[name] = [child];
2807
- slots[name]["$$slot"] = true;
2808
- delete child.props.slot;
2809
- delete vnode.props.children;
2810
- } else if (Array.isArray(vnode.props.children)) {
2811
- vnode.props.children = vnode.props.children.map((child) => {
2812
- if (!isVNode(child)) return child;
2813
- if (!("slot" in child.props)) return child;
2814
- const name = toSlotName(child.props.slot);
2815
- if (Array.isArray(slots[name])) {
2816
- slots[name].push(child);
2817
- } else {
2818
- slots[name] = [child];
2819
- slots[name]["$$slot"] = true;
2820
- }
2821
- delete child.props.slot;
2822
- return Empty;
2823
- }).filter((v) => v !== Empty);
2824
- }
2825
- Object.assign(vnode.props, slots);
2826
- }
2827
- function markRawChildren(child) {
2828
- if (typeof child === "string") return markHTMLString(child);
2829
- if (Array.isArray(child)) return child.map((c) => markRawChildren(c));
2830
- return child;
2831
- }
2832
- function transformSetDirectives(vnode) {
2833
- if (!("set:html" in vnode.props || "set:text" in vnode.props)) return;
2834
- if ("set:html" in vnode.props) {
2835
- const children = markRawChildren(vnode.props["set:html"]);
2836
- delete vnode.props["set:html"];
2837
- Object.assign(vnode.props, { children });
2838
- return;
2839
- }
2840
- if ("set:text" in vnode.props) {
2841
- const children = vnode.props["set:text"];
2842
- delete vnode.props["set:text"];
2843
- Object.assign(vnode.props, { children });
2844
- return;
2845
- }
2846
- }
2847
- function createVNode(type, props) {
2848
- const vnode = {
2849
- [Renderer]: "astro:jsx",
2850
- [AstroJSX]: true,
2851
- type,
2852
- props: props ?? {}
2853
- };
2854
- transformSetDirectives(vnode);
2855
- transformSlots(vnode);
2856
- return vnode;
2857
- }
2858
-
2859
- export { clientAddressSymbol as $, AstroError as A, ResponseSentError as B, MiddlewareNotAResponse as C, originPathnameSymbol as D, RewriteWithBodyUsed as E, InvalidGetStaticPathsEntry as F, GetStaticPathsRequired as G, GetStaticPathsExpectedParams as H, InvalidGetStaticPathsReturn as I, GetStaticPathsInvalidRouteParam as J, DEFAULT_404_COMPONENT as K, PrerenderDynamicEndpointPathCollide as L, MiddlewareNoDataOrNextCalled as M, NoMatchingStaticPathFound as N, ReservedSlotName as O, PageNumberParamNotFound as P, renderSlotToString as Q, RenderUndefinedEntryError as R, chunkToString as S, isRenderInstruction as T, UnknownContentCollectionError as U, ForbiddenRewrite as V, SessionStorageSaveError as W, SessionStorageInitError as X, ASTRO_VERSION as Y, LocalsReassigned as Z, PrerenderClientAddressNotAvailable as _, createAstro as a, ClientAddressNotAvailable as a0, StaticClientAddressNotAvailable as a1, AstroResponseHeadersReassigned as a2, responseSentSymbol as a3, renderPage as a4, REWRITE_DIRECTIVE_HEADER_KEY as a5, REWRITE_DIRECTIVE_HEADER_VALUE as a6, renderEndpoint as a7, LocalsNotAnObject as a8, REROUTABLE_STATUS_CODES as a9, NOOP_MIDDLEWARE_HEADER as aa, MissingSharp as ab, ExpectedImage as ac, LocalImageUsedWrongly as ad, MissingImageDimension as ae, UnsupportedImageFormat as af, IncompatibleDescriptorOptions as ag, UnsupportedImageConversion as ah, toStyleString as ai, NoImageMetadata as aj, FailedToFetchRemoteImageDimensions as ak, ExpectedImageOptions as al, ExpectedNotESMImage as am, InvalidImageService as an, ImageMissingAlt as ao, spreadAttributes as ap, Fragment as aq, __astro_tag_component__ as ar, renderTemplate as b, createComponent as c, addAttribute as d, renderHead as e, renderUniqueStylesheet as f, renderScriptElement as g, createHeadAndContent as h, renderScript as i, renderSlot as j, renderTransition as k, createTransitionScope as l, maybeRenderHead as m, decodeKey as n, renderJSX as o, createVNode as p, AstroJSX as q, renderComponent as r, AstroUserError as s, decryptString as t, unescapeHTML as u, createSlotValueFromString as v, isAstroComponentFactory as w, ROUTE_TYPE_HEADER as x, REROUTE_DIRECTIVE_HEADER as y, i18nNoLocaleFoundInPath as z };