cloudcommerce 0.26.2 → 0.26.3

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 (132) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/ecomplus-stores/barra-doce/functions/many/package.json +3 -3
  3. package/ecomplus-stores/barra-doce/functions/ssr/index.js +0 -1
  4. package/ecomplus-stores/barra-doce/functions/ssr/package.json +8 -8
  5. package/ecomplus-stores/barra-doce/functions/ssr/src/components/CartItem.vue +64 -0
  6. package/ecomplus-stores/barra-doce/functions/ssr/src/components/CartSidebar.vue +38 -7
  7. package/ecomplus-stores/barra-doce/functions/ssr/src/components/Prices.vue +2 -3
  8. package/ecomplus-stores/barra-doce/functions/ssr/src/components/ShopHeader.vue +8 -4
  9. package/ecomplus-stores/barra-doce/functions/with-apps/package.json +3 -3
  10. package/ecomplus-stores/barra-doce/package.json +2 -2
  11. package/ecomplus-stores/iluminim/functions/many/package.json +3 -3
  12. package/ecomplus-stores/iluminim/functions/ssr/package.json +8 -8
  13. package/ecomplus-stores/iluminim/functions/ssr/src/components/CartItem.vue +64 -0
  14. package/ecomplus-stores/iluminim/functions/ssr/src/components/CartSidebar.vue +37 -6
  15. package/ecomplus-stores/iluminim/functions/ssr/src/components/Prices.vue +2 -3
  16. package/ecomplus-stores/iluminim/functions/ssr/src/components/ShopHeader.vue +6 -2
  17. package/ecomplus-stores/iluminim/functions/with-apps/package.json +3 -3
  18. package/ecomplus-stores/iluminim/package.json +2 -2
  19. package/package.json +3 -3
  20. package/packages/api/package.json +1 -1
  21. package/packages/apps/affilate-program/package.json +1 -1
  22. package/packages/apps/correios/package.json +1 -1
  23. package/packages/apps/custom-payment/package.json +1 -1
  24. package/packages/apps/custom-shipping/package.json +1 -1
  25. package/packages/apps/datafrete/package.json +1 -1
  26. package/packages/apps/discounts/package.json +1 -1
  27. package/packages/apps/emails/package.json +2 -2
  28. package/packages/apps/fb-conversions/package.json +1 -1
  29. package/packages/apps/flash-courier/package.json +1 -1
  30. package/packages/apps/frenet/package.json +1 -1
  31. package/packages/apps/galaxpay/package.json +1 -1
  32. package/packages/apps/google-analytics/package.json +1 -1
  33. package/packages/apps/jadlog/package.json +1 -1
  34. package/packages/apps/loyalty-points/package.json +1 -1
  35. package/packages/apps/melhor-envio/package.json +1 -1
  36. package/packages/apps/mercadopago/package.json +1 -1
  37. package/packages/apps/pagarme/package.json +1 -1
  38. package/packages/apps/paghiper/package.json +1 -1
  39. package/packages/apps/pix/package.json +1 -1
  40. package/packages/apps/tiny-erp/package.json +1 -1
  41. package/packages/apps/webhooks/package.json +1 -1
  42. package/packages/cli/package.json +1 -1
  43. package/packages/config/package.json +1 -1
  44. package/packages/emails/package.json +1 -1
  45. package/packages/eslint/package.json +3 -3
  46. package/packages/events/package.json +1 -1
  47. package/packages/feeds/package.json +1 -1
  48. package/packages/firebase/package.json +1 -1
  49. package/packages/i18n/package.json +1 -1
  50. package/packages/modules/lib/firebase/functions-checkout/request-to-module.js +2 -2
  51. package/packages/modules/lib/firebase/functions-checkout/request-to-module.js.map +1 -1
  52. package/packages/modules/lib/firebase/functions-checkout/utils.js +21 -9
  53. package/packages/modules/lib/firebase/functions-checkout/utils.js.map +1 -1
  54. package/packages/modules/package.json +2 -2
  55. package/packages/modules/schemas/@checkout.cjs +0 -1
  56. package/packages/modules/src/firebase/functions-checkout/request-to-module.ts +2 -2
  57. package/packages/modules/src/firebase/functions-checkout/utils.ts +23 -9
  58. package/packages/passport/package.json +1 -1
  59. package/packages/ssr/package.json +2 -2
  60. package/packages/storefront/dist/client/_astro/{Carousel.926668f2.js → Carousel.0b24e2cb.js} +1 -1
  61. package/packages/storefront/dist/client/_astro/CartSidebar.2731d333.js +1 -0
  62. package/packages/storefront/dist/client/_astro/{HeroSlider.1f0524aa.js → HeroSlider.a70b2582.js} +1 -1
  63. package/packages/storefront/dist/client/_astro/{PitchBar.7407eeaf.js → PitchBar.13991988.js} +1 -1
  64. package/packages/storefront/dist/client/_astro/{Prices.562a32ab.js → Prices.cdfa346a.js} +1 -1
  65. package/packages/storefront/dist/client/_astro/{ProductShelf.763cd2ca.js → ProductShelf.619c56a5.js} +1 -1
  66. package/packages/storefront/dist/client/_astro/SearchModal.117a477d.js +1 -0
  67. package/packages/storefront/dist/client/_astro/{ShopHeader.126900a6.js → ShopHeader.2c2fded7.js} +2 -2
  68. package/packages/storefront/dist/client/_astro/_...slug_.b693913e.css +1 -0
  69. package/packages/storefront/dist/client/_astro/{_plugin-vue_export-helper.ee681fa8.js → _plugin-vue_export-helper.fc5e2f5b.js} +1 -1
  70. package/packages/storefront/dist/client/_astro/{api.a2eda23e.js → api.39f40cd8.js} +1 -1
  71. package/packages/storefront/dist/client/_astro/client.a5d2898b.js +1 -0
  72. package/packages/storefront/dist/client/_astro/{firebase-app.93857bfb.js → firebase-app.8c541cce.js} +3 -3
  73. package/packages/storefront/dist/client/_astro/{format-money.923559cc.js → format-money.86f14860.js} +1 -1
  74. package/packages/storefront/dist/client/_astro/hoisted.d90361ee.js +1 -0
  75. package/packages/storefront/dist/client/_astro/{img.ec6ba316.js → img.d4891d80.js} +1 -1
  76. package/packages/storefront/dist/client/_astro/index.33801818.js +1 -0
  77. package/packages/storefront/dist/client/_astro/{modules-info.48980668.js → modules-info.ec412b24.js} +1 -1
  78. package/packages/storefront/dist/client/_empty-middleware.mjs +3 -0
  79. package/packages/storefront/dist/client/chunks/CartSidebar.0ce1e999.mjs +382 -0
  80. package/packages/storefront/dist/client/chunks/SearchModal.f603145b.mjs +32 -0
  81. package/packages/storefront/dist/client/chunks/astro.11be33ee.mjs +1424 -0
  82. package/packages/storefront/dist/{server/chunks/pages/_...slug_.astro.fd8a229f.mjs → client/chunks/pages/_...slug_.astro.ec6517ba.mjs} +360 -274
  83. package/packages/storefront/dist/{server/chunks/pages/account.astro.3b21bff8.mjs → client/chunks/pages/account.astro.3d2605e6.mjs} +2 -10
  84. package/packages/storefront/dist/{server/chunks/pages/index.astro.dab642f5.mjs → client/chunks/pages/index.astro.8ad03206.mjs} +167 -17
  85. package/packages/storefront/dist/{server/chunks/pages/~fallback.astro.7630c0d6.mjs → client/chunks/pages/~fallback.astro.d31d20b4.mjs} +8 -20
  86. package/packages/storefront/dist/client/chunks/sharp.3f154e38.mjs +74 -0
  87. package/packages/storefront/dist/client/manifest.e39eb543.mjs +79 -0
  88. package/packages/storefront/dist/client/pages/_---slug_.astro.mjs +23 -0
  89. package/packages/storefront/dist/client/pages/app/account.astro.mjs +23 -0
  90. package/packages/storefront/dist/client/pages/app.astro.mjs +23 -0
  91. package/packages/storefront/dist/client/pages/index.astro.mjs +23 -0
  92. package/packages/storefront/dist/client/pages/~fallback.astro.mjs +23 -0
  93. package/packages/storefront/dist/client/registerSW.js +1 -0
  94. package/packages/storefront/dist/client/renderers.mjs +369 -0
  95. package/packages/storefront/dist/client/sw.js +1 -1
  96. package/packages/storefront/dist/server/chunks/{CartSidebar.2b555408.mjs → CartSidebar.cca9fdd3.mjs} +14 -24
  97. package/packages/storefront/dist/server/chunks/{SearchModal.f418e188.mjs → SearchModal.a680efae.mjs} +8 -19
  98. package/packages/storefront/dist/server/chunks/_...f7cdc954.mjs +24 -0
  99. package/packages/storefront/dist/server/chunks/account@_@astro.fa8b921b.mjs +24 -0
  100. package/packages/storefront/dist/server/chunks/{astro.bb5b7191.mjs → astro.440a2e08.mjs} +149 -1859
  101. package/packages/storefront/dist/server/chunks/image-endpoint@_@js.802bf648.mjs +24 -0
  102. package/packages/storefront/dist/server/chunks/index@_@astro.a122f091.mjs +24 -0
  103. package/packages/storefront/dist/server/chunks/index@_@astro.da98dcbe.mjs +24 -0
  104. package/packages/storefront/dist/server/chunks/pages/_...slug_.astro.08ba5973.mjs +3930 -0
  105. package/packages/storefront/dist/server/chunks/pages/account.astro.f11f26f3.mjs +15 -0
  106. package/packages/storefront/dist/server/chunks/pages/image-endpoint.js.a9374d3e.mjs +238 -0
  107. package/packages/storefront/dist/server/chunks/pages/index.astro.079f316a.mjs +1650 -0
  108. package/packages/storefront/dist/server/chunks/pages/~fallback.astro.01594623.mjs +55 -0
  109. package/packages/storefront/dist/server/chunks/sharp.52841bb4.mjs +75 -0
  110. package/packages/storefront/dist/server/chunks/~fallback@_@astro.876a97c5.mjs +24 -0
  111. package/packages/storefront/dist/server/entry.mjs +1167 -2360
  112. package/packages/storefront/dist/server/manifest.12e7a10c.mjs +561 -0
  113. package/packages/storefront/dist/server/renderers.mjs +10 -21
  114. package/packages/storefront/package.json +6 -6
  115. package/packages/storefront/src/lib/layouts/BaseHead.astro +3 -2
  116. package/packages/test-base/package.json +1 -1
  117. package/packages/types/modules/@checkout:params.d.ts +1 -1
  118. package/packages/types/package.json +1 -1
  119. package/ecomplus-stores/iluminim/.ecomplus.cd.json +0 -5
  120. package/packages/storefront/dist/client/_astro/CartSidebar.eadba34f.js +0 -1
  121. package/packages/storefront/dist/client/_astro/SearchModal.cffd4c2d.js +0 -1
  122. package/packages/storefront/dist/client/_astro/_...slug_.36cd433d.css +0 -1
  123. package/packages/storefront/dist/client/_astro/client.e6d9439a.js +0 -1
  124. package/packages/storefront/dist/client/_astro/hoisted.572313d6.js +0 -1
  125. package/packages/storefront/dist/client/_astro/index.709ac149.js +0 -1
  126. package/packages/storefront/dist/server/chunks/_...d32bcc0c.mjs +0 -35
  127. package/packages/storefront/dist/server/chunks/account@_@astro.0106855f.mjs +0 -35
  128. package/packages/storefront/dist/server/chunks/endpoint@_@js.35807882.mjs +0 -35
  129. package/packages/storefront/dist/server/chunks/index@_@astro.477f5af1.mjs +0 -35
  130. package/packages/storefront/dist/server/chunks/index@_@astro.e5a61d6e.mjs +0 -35
  131. package/packages/storefront/dist/server/chunks/pages/endpoint.js.247079ba.mjs +0 -119
  132. package/packages/storefront/dist/server/chunks/~fallback@_@astro.65227dd7.mjs +0 -35
@@ -1,12 +1,4 @@
1
- import { compile } from 'path-to-regexp';
2
- import { serialize, parse } from 'cookie';
3
- import { joinPaths, slash, prependForwardSlash, removeTrailingForwardSlash, collapseDuplicateSlashes } from '@astrojs/internal-helpers/path';
4
- import { yellow, dim, bold, cyan, red, reset } from 'kleur/colors';
5
- import 'node:fs';
6
- import 'node:http';
7
- import { TLSSocket } from 'node:tls';
8
- import mime from 'mime';
9
- import 'string-width';
1
+ import { clsx } from 'clsx';
10
2
  import { escape } from 'html-escaper';
11
3
 
12
4
  const ClientAddressNotAvailable = {
@@ -60,11 +52,11 @@ const NoClientOnlyHint = {
60
52
  message: (componentName) => `Unable to render \`${componentName}\`. When using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.`,
61
53
  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`
62
54
  };
63
- const InvalidGetStaticPathParam = {
64
- name: "InvalidGetStaticPathParam",
65
- title: "Invalid value returned by a `getStaticPaths` path.",
66
- message: (paramType) => `Invalid params given to \`getStaticPaths\` path. Expected an \`object\`, got \`${paramType}\``,
67
- hint: "See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths."
55
+ const InvalidGetStaticPathsEntry = {
56
+ name: "InvalidGetStaticPathsEntry",
57
+ title: "Invalid entry inside getStaticPath's return value",
58
+ message: (entryType) => `Invalid entry returned by getStaticPaths. Expected an object, got \`${entryType}\``,
59
+ hint: "If you're using a `.map` call, you might be looking for `.flatMap()` instead. See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths."
68
60
  };
69
61
  const InvalidGetStaticPathsReturn = {
70
62
  name: "InvalidGetStaticPathsReturn",
@@ -116,12 +108,48 @@ const PageNumberParamNotFound = {
116
108
  message: (paramName) => `[paginate()] page number param \`${paramName}\` not found in your filepath.`,
117
109
  hint: "Rename your file to `[page].astro` or `[...page].astro`."
118
110
  };
111
+ const ImageMissingAlt = {
112
+ name: "ImageMissingAlt",
113
+ title: "Missing alt property.",
114
+ message: "The alt property is required.",
115
+ hint: "The `alt` property is important for the purpose of accessibility, without it users using screen readers or other assistive technologies won't be able to understand what your image is supposed to represent. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-alt for more information."
116
+ };
117
+ const InvalidImageService = {
118
+ name: "InvalidImageService",
119
+ title: "Error while loading image service.",
120
+ message: "There was an error loading the configured image service. Please see the stack trace for more information."
121
+ };
122
+ const MissingImageDimension = {
123
+ name: "MissingImageDimension",
124
+ title: "Missing image dimensions",
125
+ message: (missingDimension, imageURL) => `Missing ${missingDimension === "both" ? "width and height attributes" : `${missingDimension} attribute`} for ${imageURL}. When using remote images, both dimensions are always required in order to avoid CLS.`,
126
+ 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)."
127
+ };
128
+ const UnsupportedImageFormat = {
129
+ name: "UnsupportedImageFormat",
130
+ title: "Unsupported image format",
131
+ message: (format, imagePath, supportedFormats) => `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join(
132
+ ", "
133
+ )} are supported by our image services.`,
134
+ hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for."
135
+ };
119
136
  const PrerenderDynamicEndpointPathCollide = {
120
137
  name: "PrerenderDynamicEndpointPathCollide",
121
138
  title: "Prerendered dynamic endpoint has path collision.",
122
139
  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.`,
123
140
  hint: (filename) => `Rename \`${filename}\` to \`${filename.replace(/\.(js|ts)/, (m) => `.json` + m)}\``
124
141
  };
142
+ const ExpectedImage = {
143
+ name: "ExpectedImage",
144
+ title: "Expected src to be an image.",
145
+ message: (options) => `Expected \`src\` property to be either an ESM imported image or a string with the path of a remote image. Received \`${options}\`.`,
146
+ hint: "This error can often happen because of a wrong path. Make sure the path to your image is correct."
147
+ };
148
+ const ExpectedImageOptions = {
149
+ name: "ExpectedImageOptions",
150
+ title: "Expected image options.",
151
+ message: (options) => `Expected getImage() parameter to be an object. Received \`${options}\`.`
152
+ };
125
153
  const ResponseSentError = {
126
154
  name: "ResponseSentError",
127
155
  title: "Unable to set response.",
@@ -143,6 +171,11 @@ const LocalsNotAnObject = {
143
171
  message: "`locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted.",
144
172
  hint: "If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`."
145
173
  };
174
+ const LocalImageUsedWrongly = {
175
+ name: "LocalImageUsedWrongly",
176
+ title: "ESM imported images must be passed as-is.",
177
+ message: (imageFilePath) => `\`Image\`'s and \`getImage\`'s \`src\` parameter must be an imported image or an URL, it cannot be a filepath. Received \`${imageFilePath}\`.`
178
+ };
146
179
  const AstroGlobUsedOutside = {
147
180
  name: "AstroGlobUsedOutside",
148
181
  title: "Astro.glob() used outside of an Astro file.",
@@ -154,6 +187,12 @@ const AstroGlobNoMatch = {
154
187
  title: "Astro.glob() did not match any files.",
155
188
  message: (globStr) => `\`Astro.glob(${globStr})\` did not return any matching files. Check the pattern for typos.`
156
189
  };
190
+ const MissingSharp = {
191
+ name: "MissingSharp",
192
+ title: "Could not find Sharp.",
193
+ message: "Could not find Sharp. Please install Sharp (`sharp`) manually into your project.",
194
+ 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."
195
+ };
157
196
 
158
197
  function normalizeLF(code) {
159
198
  return code.replace(/\r\n|\r(?!\n)|\n/g, "\n");
@@ -191,9 +230,13 @@ function codeFrame(src, loc) {
191
230
  }
192
231
 
193
232
  class AstroError extends Error {
233
+ loc;
234
+ title;
235
+ hint;
236
+ frame;
237
+ type = "AstroError";
194
238
  constructor(props, ...params) {
195
239
  super(...params);
196
- this.type = "AstroError";
197
240
  const { name, title, message, stack, location, hint, frame } = props;
198
241
  this.title = title;
199
242
  this.name = name;
@@ -223,6 +266,22 @@ class AstroError extends Error {
223
266
  return err.type === "AstroError";
224
267
  }
225
268
  }
269
+ class AstroUserError extends Error {
270
+ type = "AstroUserError";
271
+ /**
272
+ * A message that explains to the user how they can fix the error.
273
+ */
274
+ hint;
275
+ name = "AstroUserError";
276
+ constructor(message, hint) {
277
+ super();
278
+ this.message = message;
279
+ this.hint = hint;
280
+ }
281
+ static is(err) {
282
+ return err.type === "AstroUserError";
283
+ }
284
+ }
226
285
 
227
286
  function validateArgs(args) {
228
287
  if (args.length !== 3)
@@ -232,8 +291,7 @@ function validateArgs(args) {
232
291
  return true;
233
292
  }
234
293
  function baseCreateComponent(cb, moduleId, propagation) {
235
- var _a;
236
- const name = ((_a = moduleId == null ? void 0 : moduleId.split("/").pop()) == null ? void 0 : _a.replace(".astro", "")) ?? "";
294
+ const name = moduleId?.split("/").pop()?.replace(".astro", "") ?? "";
237
295
  const fn = (...args) => {
238
296
  if (!validateArgs(args)) {
239
297
  throw new AstroError({
@@ -261,7 +319,7 @@ function createComponent(arg1, moduleId, propagation) {
261
319
  }
262
320
  }
263
321
 
264
- const ASTRO_VERSION = "2.10.14";
322
+ const ASTRO_VERSION = "3.0.5";
265
323
 
266
324
  function createAstroGlobFn() {
267
325
  const globHandler = (importMetaGlobResult) => {
@@ -290,24 +348,36 @@ function createAstro(site) {
290
348
  };
291
349
  }
292
350
 
293
- function getHandlerFromModule(mod, method) {
351
+ function getHandlerFromModule(mod, method, logger) {
352
+ const lowerCaseMethod = method.toLowerCase();
353
+ if (mod[lowerCaseMethod]) {
354
+ logger.warn(
355
+ "astro",
356
+ `Lower case endpoint names are deprecated and will not be supported in Astro 4.0. Rename the endpoint ${lowerCaseMethod} to ${method}.`
357
+ );
358
+ }
294
359
  if (mod[method]) {
295
360
  return mod[method];
296
361
  }
362
+ if (mod[lowerCaseMethod]) {
363
+ return mod[lowerCaseMethod];
364
+ }
297
365
  if (method === "delete" && mod["del"]) {
298
366
  return mod["del"];
299
367
  }
300
368
  if (mod["all"]) {
301
369
  return mod["all"];
302
370
  }
371
+ if (mod["ALL"]) {
372
+ return mod["ALL"];
373
+ }
303
374
  return void 0;
304
375
  }
305
- async function renderEndpoint(mod, context, ssr) {
306
- var _a;
307
- const { request, params } = context;
308
- const chosenMethod = (_a = request.method) == null ? void 0 : _a.toLowerCase();
309
- const handler = getHandlerFromModule(mod, chosenMethod);
310
- if (!ssr && ssr === false && chosenMethod && chosenMethod !== "get") {
376
+ async function renderEndpoint(mod, context, ssr, logger) {
377
+ const { request } = context;
378
+ const chosenMethod = request.method?.toUpperCase();
379
+ const handler = getHandlerFromModule(mod, chosenMethod, logger);
380
+ if (!ssr && ssr === false && chosenMethod && chosenMethod !== "GET" && chosenMethod !== "get") {
311
381
  console.warn(`
312
382
  ${chosenMethod} requests are not available when building a static site. Update your config to \`output: 'server'\` or \`output: 'hybrid'\` with an \`export const prerender = false\` to handle ${chosenMethod} requests.`);
313
383
  }
@@ -320,30 +390,10 @@ ${chosenMethod} requests are not available when building a static site. Update y
320
390
  });
321
391
  return response;
322
392
  }
323
- if (handler.length > 1) {
324
- console.warn(`
325
- API routes with 2 arguments have been deprecated. Instead they take a single argument in the form of:
326
-
327
- export function get({ params, request }) {
328
- //...
329
- }
330
-
331
- Update your code to remove this warning.`);
332
- }
333
393
  const proxy = new Proxy(context, {
334
394
  get(target, prop) {
335
395
  if (prop in target) {
336
396
  return Reflect.get(target, prop);
337
- } else if (prop in params) {
338
- console.warn(`
339
- API routes no longer pass params as the first argument. Instead an object containing a params property is provided in the form of:
340
-
341
- export function get({ params }) {
342
- // ...
343
- }
344
-
345
- Update your code to remove this warning.`);
346
- return Reflect.get(params, prop);
347
397
  } else {
348
398
  return void 0;
349
399
  }
@@ -352,28 +402,6 @@ Update your code to remove this warning.`);
352
402
  return handler.call(mod, proxy, request);
353
403
  }
354
404
 
355
- function serializeListValue(value) {
356
- const hash = {};
357
- push(value);
358
- return Object.keys(hash).join(" ");
359
- function push(item) {
360
- if (item && typeof item.forEach === "function")
361
- item.forEach(push);
362
- else if (item === Object(item))
363
- Object.keys(item).forEach((name) => {
364
- if (item[name])
365
- push(name);
366
- });
367
- else {
368
- item = item === false || item == null ? "" : String(item).trim();
369
- if (item) {
370
- item.split(/\s+/).forEach((name) => {
371
- hash[name] = true;
372
- });
373
- }
374
- }
375
- }
376
- }
377
405
  function isPromise(value) {
378
406
  return !!value && typeof value === "object" && typeof value.then === "function";
379
407
  }
@@ -458,6 +486,11 @@ function unescapeHTML(str) {
458
486
  return markHTMLString(str);
459
487
  }
460
488
 
489
+ const AstroJSX = "astro:jsx";
490
+ function isVNode(vnode) {
491
+ return vnode && typeof vnode === "object" && vnode[AstroJSX];
492
+ }
493
+
461
494
  const RenderInstructionSymbol = Symbol.for("astro:render");
462
495
  function createRenderInstruction(instruction) {
463
496
  return Object.defineProperty(instruction, RenderInstructionSymbol, {
@@ -614,10 +647,6 @@ function extractDirectives(inputProps, clientDirectives) {
614
647
  break;
615
648
  }
616
649
  }
617
- } else if (key === "class:list") {
618
- if (value) {
619
- extracted.props[key.slice(0, -5)] = serializeListValue(value);
620
- }
621
650
  } else {
622
651
  extracted.props[key] = value;
623
652
  }
@@ -749,7 +778,7 @@ function isHeadAndContent(obj) {
749
778
  return typeof obj === "object" && !!obj[headAndContentSym];
750
779
  }
751
780
 
752
- var astro_island_prebuilt_default = `(()=>{var d;{let p={0:t=>u(t),1:t=>l(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(l(t)),5:t=>new Set(l(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)},h=t=>{let[e,n]=t;return e in p?p[e](n):void 0},l=t=>t.map(h),u=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([e,n])=>[e,h(n)]));customElements.get("astro-island")||customElements.define("astro-island",(d=class extends HTMLElement{constructor(){super(...arguments);this.hydrate=async()=>{var i;if(!this.hydrator||!this.isConnected)return;let e=(i=this.parentElement)==null?void 0:i.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let n=this.querySelectorAll("astro-slot"),o={},a=this.querySelectorAll("template[data-astro-template]");for(let r of a){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(o[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of n){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(o[r.getAttribute("name")||"default"]=r.innerHTML)}let c;try{c=this.hasAttribute("props")?u(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",y=this.getAttribute("component-export");throw y&&(s+=\` (export \${y})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}await this.hydrator(this)(this.Component,c,o,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))}}connectedCallback(){!this.hasAttribute("await-children")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((e,n)=>{n.disconnect(),setTimeout(()=>this.childrenConnectedCallback(),0)}).observe(this,{childList:!0})}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}start(){let e=JSON.parse(this.getAttribute("opts")),n=this.getAttribute("client");if(Astro[n]===void 0){window.addEventListener(\`astro:\${n}\`,()=>this.start(),{once:!0});return}Astro[n](async()=>{let o=this.getAttribute("renderer-url"),[a,{default:c}]=await Promise.all([import(this.getAttribute("component-url")),o?import(o):()=>()=>{}]),i=this.getAttribute("component-export")||"default";if(!i.includes("."))this.Component=a[i];else{this.Component=a;for(let r of i.split("."))this.Component=this.Component[r]}return this.hydrator=c,this.hydrate},e,this)}attributeChangedCallback(){this.hydrate()}},d.observedAttributes=["props"],d))}})();`;
781
+ var astro_island_prebuilt_default = `(()=>{var b=Object.defineProperty;var f=(a,s,i)=>s in a?b(a,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):a[s]=i;var d=(a,s,i)=>(f(a,typeof s!="symbol"?s+"":s,i),i);var u;{let a={0:t=>m(t),1:t=>i(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(i(t)),5:t=>new Set(i(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)},s=t=>{let[e,r]=t;return e in a?a[e](r):void 0},i=t=>t.map(s),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([e,r])=>[e,s(r)]));customElements.get("astro-island")||customElements.define("astro-island",(u=class extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var l;if(!this.hydrator||!this.isConnected)return;let e=(l=this.parentElement)==null?void 0:l.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let r=this.querySelectorAll("astro-slot"),c={},h=this.querySelectorAll("template[data-astro-template]");for(let n of h){let o=n.closest(this.tagName);o!=null&&o.isSameNode(this)&&(c[n.getAttribute("data-astro-template")||"default"]=n.innerHTML,n.remove())}for(let n of r){let o=n.closest(this.tagName);o!=null&&o.isSameNode(this)&&(c[n.getAttribute("name")||"default"]=n.innerHTML)}let p;try{p=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(n){let o=this.getAttribute("component-url")||"<unknown>",y=this.getAttribute("component-export");throw y&&(o+=\` (export \${y})\`),console.error(\`[hydrate] Error parsing props for component \${o}\`,this.getAttribute("props"),n),n}await this.hydrator(this)(this.Component,p,c,{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(){!this.hasAttribute("await-children")||this.firstChild?this.childrenConnectedCallback():new MutationObserver((e,r)=>{r.disconnect(),setTimeout(()=>this.childrenConnectedCallback(),0)}).observe(this,{childList:!0})}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}start(){let e=JSON.parse(this.getAttribute("opts")),r=this.getAttribute("client");if(Astro[r]===void 0){window.addEventListener(\`astro:\${r}\`,()=>this.start(),{once:!0});return}Astro[r](async()=>{let c=this.getAttribute("renderer-url"),[h,{default:p}]=await Promise.all([import(this.getAttribute("component-url")),c?import(c):()=>()=>{}]),l=this.getAttribute("component-export")||"default";if(!l.includes("."))this.Component=h[l];else{this.Component=h;for(let n of l.split("."))this.Component=this.Component[n]}return this.hydrator=p,this.hydrate},e,this)}attributeChangedCallback(){this.hydrate()}},d(u,"observedAttributes",["props"]),u))}})();`;
753
782
 
754
783
  const ISLAND_STYLES = `<style>astro-island,astro-slot,astro-static-slot{display:contents}</style>`;
755
784
  function determineIfNeedsHydrationScript(result) {
@@ -801,15 +830,12 @@ const kebab = (k) => k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, (match) =>
801
830
  const toStyleString = (obj) => Object.entries(obj).map(([k, v]) => {
802
831
  if (k[0] !== "-" && k[1] !== "-")
803
832
  return `${kebab(k)}:${v}`;
804
- if (kebab(k) !== k)
805
- return `${kebab(k)}:var(${k});${k}:${v}`;
806
833
  return `${k}:${v}`;
807
834
  }).join(";");
808
835
  function defineScriptVars(vars) {
809
- var _a;
810
836
  let output = "";
811
837
  for (const [key, value] of Object.entries(vars)) {
812
- output += `const ${toIdent(key)} = ${(_a = JSON.stringify(value)) == null ? void 0 : _a.replace(
838
+ output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace(
813
839
  /<\/script>/g,
814
840
  "\\x3C/script>"
815
841
  )};
@@ -840,7 +866,7 @@ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the
840
866
  return "";
841
867
  }
842
868
  if (key === "class:list") {
843
- const listValue = toAttributeString(serializeListValue(value), shouldEscape);
869
+ const listValue = toAttributeString(clsx(value), shouldEscape);
844
870
  if (listValue === "") {
845
871
  return "";
846
872
  }
@@ -935,6 +961,8 @@ function* maybeRenderHead() {
935
961
 
936
962
  const slotString = Symbol.for("astro:slot-string");
937
963
  class SlotString extends HTMLString {
964
+ instructions;
965
+ [slotString];
938
966
  constructor(content, instructions) {
939
967
  super(content);
940
968
  this.instructions = instructions;
@@ -1102,11 +1130,15 @@ async function renderChild(destination, child) {
1102
1130
  }
1103
1131
  }
1104
1132
 
1105
- var _a$1;
1106
1133
  const astroComponentInstanceSym = Symbol.for("astro.componentInstance");
1107
1134
  class AstroComponentInstance {
1135
+ [astroComponentInstanceSym] = true;
1136
+ result;
1137
+ props;
1138
+ slotValues;
1139
+ factory;
1140
+ returnValue;
1108
1141
  constructor(result, props, slots, factory) {
1109
- this[_a$1] = true;
1110
1142
  this.result = result;
1111
1143
  this.props = props;
1112
1144
  this.factory = factory;
@@ -1137,7 +1169,6 @@ class AstroComponentInstance {
1137
1169
  }
1138
1170
  }
1139
1171
  }
1140
- _a$1 = astroComponentInstanceSym;
1141
1172
  function validateComponentProps(props, displayName) {
1142
1173
  if (props != null) {
1143
1174
  for (const prop of Object.keys(props)) {
@@ -1161,11 +1192,13 @@ function isAstroComponentInstance(obj) {
1161
1192
  return typeof obj === "object" && !!obj[astroComponentInstanceSym];
1162
1193
  }
1163
1194
 
1164
- var _a;
1165
1195
  const renderTemplateResultSym = Symbol.for("astro.renderTemplateResult");
1166
1196
  class RenderTemplateResult {
1197
+ [renderTemplateResultSym] = true;
1198
+ htmlParts;
1199
+ expressions;
1200
+ error;
1167
1201
  constructor(htmlParts, expressions) {
1168
- this[_a] = true;
1169
1202
  this.htmlParts = htmlParts;
1170
1203
  this.error = void 0;
1171
1204
  this.expressions = expressions.map((expression) => {
@@ -1198,7 +1231,6 @@ class RenderTemplateResult {
1198
1231
  }
1199
1232
  }
1200
1233
  }
1201
- _a = renderTemplateResultSym;
1202
1234
  function isRenderTemplateResult(obj) {
1203
1235
  return typeof obj === "object" && !!obj[renderTemplateResultSym];
1204
1236
  }
@@ -1276,7 +1308,7 @@ async function renderToReadableStream(result, componentFactory, props, children,
1276
1308
  } catch (e) {
1277
1309
  if (AstroError.is(e) && !e.loc) {
1278
1310
  e.setLocation({
1279
- file: route == null ? void 0 : route.component
1311
+ file: route?.component
1280
1312
  });
1281
1313
  }
1282
1314
  setTimeout(() => controller.error(e), 0);
@@ -1292,9 +1324,9 @@ async function callComponentAsTemplateResultOrResponse(result, componentFactory,
1292
1324
  } else if (!isRenderTemplateResult(factoryResult)) {
1293
1325
  throw new AstroError({
1294
1326
  ...OnlyResponseCanBeReturned,
1295
- message: OnlyResponseCanBeReturned.message(route == null ? void 0 : route.route, typeof factoryResult),
1327
+ message: OnlyResponseCanBeReturned.message(route?.route, typeof factoryResult),
1296
1328
  location: {
1297
- file: route == null ? void 0 : route.component
1329
+ file: route?.component
1298
1330
  }
1299
1331
  });
1300
1332
  }
@@ -1324,7 +1356,7 @@ async function renderHTMLElement(result, constructor, props, slots) {
1324
1356
  attrHTML += ` ${attr}="${toAttributeString(await props[attr])}"`;
1325
1357
  }
1326
1358
  return markHTMLString(
1327
- `<${name}${attrHTML}>${await renderSlotToString(result, slots == null ? void 0 : slots.default)}</${name}>`
1359
+ `<${name}${attrHTML}>${await renderSlotToString(result, slots?.default)}</${name}>`
1328
1360
  );
1329
1361
  }
1330
1362
  function getHTMLElementName(constructor) {
@@ -1338,7 +1370,7 @@ function getHTMLElementName(constructor) {
1338
1370
  const needsHeadRenderingSymbol = Symbol.for("astro.needsHeadRendering");
1339
1371
  const rendererAliases = /* @__PURE__ */ new Map([["solid", "solid-js"]]);
1340
1372
  function guessRenderers(componentUrl) {
1341
- const extname = componentUrl == null ? void 0 : componentUrl.split(".").pop();
1373
+ const extname = componentUrl?.split(".").pop();
1342
1374
  switch (extname) {
1343
1375
  case "svelte":
1344
1376
  return ["@astrojs/svelte"];
@@ -1371,7 +1403,6 @@ function removeStaticAstroSlot(html, supportsAstroStaticSlot) {
1371
1403
  return html.replace(exp, "");
1372
1404
  }
1373
1405
  async function renderFrameworkComponent(result, displayName, Component, _props, slots = {}) {
1374
- var _a, _b, _c;
1375
1406
  if (!Component && !_props["client:only"]) {
1376
1407
  throw new Error(
1377
1408
  `Unable to render ${displayName} because it is ${Component}!
@@ -1447,7 +1478,7 @@ Did you forget to import the component or is it possible there is a typo?`
1447
1478
  renderer = validRenderers[0];
1448
1479
  }
1449
1480
  if (!renderer) {
1450
- const extname = (_a = metadata.componentUrl) == null ? void 0 : _a.split(".").pop();
1481
+ const extname = metadata.componentUrl?.split(".").pop();
1451
1482
  renderer = renderers.filter(
1452
1483
  ({ name }) => name === `@astrojs/${extname}` || name === extname
1453
1484
  )[0];
@@ -1472,7 +1503,7 @@ Did you forget to import the component or is it possible there is a typo?`
1472
1503
  ...NoMatchingRenderer,
1473
1504
  message: NoMatchingRenderer.message(
1474
1505
  metadata.displayName,
1475
- (_b = metadata == null ? void 0 : metadata.componentUrl) == null ? void 0 : _b.split(".").pop(),
1506
+ metadata?.componentUrl?.split(".").pop(),
1476
1507
  plural,
1477
1508
  validRenderers.length
1478
1509
  ),
@@ -1505,7 +1536,7 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
1505
1536
  }
1506
1537
  } else {
1507
1538
  if (metadata.hydrate === "only") {
1508
- html = await renderSlotToString(result, slots == null ? void 0 : slots.fallback);
1539
+ html = await renderSlotToString(result, slots?.fallback);
1509
1540
  } else {
1510
1541
  ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
1511
1542
  { result },
@@ -1547,18 +1578,17 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
1547
1578
  if (!hydration) {
1548
1579
  return {
1549
1580
  render(destination) {
1550
- var _a2;
1551
1581
  if (slotInstructions) {
1552
1582
  for (const instruction of slotInstructions) {
1553
1583
  destination.write(instruction);
1554
1584
  }
1555
1585
  }
1556
- if (isPage || (renderer == null ? void 0 : renderer.name) === "astro:jsx") {
1586
+ if (isPage || renderer?.name === "astro:jsx") {
1557
1587
  destination.write(html);
1558
1588
  } else if (html && html.length > 0) {
1559
1589
  destination.write(
1560
1590
  markHTMLString(
1561
- removeStaticAstroSlot(html, ((_a2 = renderer == null ? void 0 : renderer.ssr) == null ? void 0 : _a2.supportsAstroStaticSlot) ?? false)
1591
+ removeStaticAstroSlot(html, renderer?.ssr?.supportsAstroStaticSlot ?? false)
1562
1592
  )
1563
1593
  );
1564
1594
  }
@@ -1581,7 +1611,7 @@ ${serializeProps(
1581
1611
  if (html) {
1582
1612
  if (Object.keys(children).length > 0) {
1583
1613
  for (const key of Object.keys(children)) {
1584
- let tagName = ((_c = renderer == null ? void 0 : renderer.ssr) == null ? void 0 : _c.supportsAstroStaticSlot) ? !!metadata.hydrate ? "astro-slot" : "astro-static-slot" : "astro-slot";
1614
+ let tagName = renderer?.ssr?.supportsAstroStaticSlot ? !!metadata.hydrate ? "astro-slot" : "astro-static-slot" : "astro-slot";
1585
1615
  let expectedHTML = key === "default" ? `<${tagName}>` : `<${tagName} name="${key}">`;
1586
1616
  if (!html.includes(expectedHTML)) {
1587
1617
  unrenderedSlots.push(key);
@@ -1617,7 +1647,7 @@ function sanitizeElementName(tag) {
1617
1647
  return tag.trim().split(unsafe)[0].trim();
1618
1648
  }
1619
1649
  async function renderFragmentComponent(result, slots = {}) {
1620
- const children = await renderSlotToString(result, slots == null ? void 0 : slots.default);
1650
+ const children = await renderSlotToString(result, slots?.default);
1621
1651
  return {
1622
1652
  render(destination) {
1623
1653
  if (children == null)
@@ -1651,6 +1681,7 @@ async function renderComponent(result, displayName, Component, props, slots = {}
1651
1681
  if (isFragmentComponent(Component)) {
1652
1682
  return await renderFragmentComponent(result, slots);
1653
1683
  }
1684
+ props = normalizeProps(props);
1654
1685
  if (isHTMLComponent(Component)) {
1655
1686
  return await renderHTMLComponent(result, Component, props, slots);
1656
1687
  }
@@ -1659,6 +1690,17 @@ async function renderComponent(result, displayName, Component, props, slots = {}
1659
1690
  }
1660
1691
  return await renderFrameworkComponent(result, displayName, Component, props, slots);
1661
1692
  }
1693
+ function normalizeProps(props) {
1694
+ if (props["class:list"] !== void 0) {
1695
+ const value = props["class:list"];
1696
+ delete props["class:list"];
1697
+ props["class"] = clsx(props["class"], value);
1698
+ if (props["class"] === "") {
1699
+ delete props["class"];
1700
+ }
1701
+ }
1702
+ return props;
1703
+ }
1662
1704
  async function renderComponentToString(result, displayName, Component, props, slots = {}, isPage = false, route) {
1663
1705
  let str = "";
1664
1706
  let renderedFirstPageChunk = false;
@@ -1688,7 +1730,7 @@ async function renderComponentToString(result, displayName, Component, props, sl
1688
1730
  } catch (e) {
1689
1731
  if (AstroError.is(e) && !e.loc) {
1690
1732
  e.setLocation({
1691
- file: route == null ? void 0 : route.component
1733
+ file: route?.component
1692
1734
  });
1693
1735
  }
1694
1736
  throw e;
@@ -1696,7 +1738,7 @@ async function renderComponentToString(result, displayName, Component, props, sl
1696
1738
  return str;
1697
1739
  }
1698
1740
  function nonAstroPageNeedsHeadInjection(pageComponent) {
1699
- return !!(pageComponent == null ? void 0 : pageComponent[needsHeadRenderingSymbol]);
1741
+ return !!pageComponent?.[needsHeadRenderingSymbol];
1700
1742
  }
1701
1743
 
1702
1744
  const ClientOnlyPlaceholder = "astro-client-only";
@@ -1705,6 +1747,7 @@ class Skip {
1705
1747
  this.vnode = vnode;
1706
1748
  this.count = 0;
1707
1749
  }
1750
+ count;
1708
1751
  increment() {
1709
1752
  this.count++;
1710
1753
  }
@@ -1714,8 +1757,8 @@ class Skip {
1714
1757
  isCompleted() {
1715
1758
  return this.count > 2;
1716
1759
  }
1760
+ static symbol = Symbol("astro:jsx:skip");
1717
1761
  }
1718
- Skip.symbol = Symbol("astro:jsx:skip");
1719
1762
  let originalConsoleError;
1720
1763
  let consoleFilterRefs = 0;
1721
1764
  async function renderJSX(result, vnode) {
@@ -1808,7 +1851,7 @@ Did you forget to import the component or is it possible there is a typo?`);
1808
1851
  try {
1809
1852
  const output2 = await vnode.type(vnode.props ?? {});
1810
1853
  let renderResult;
1811
- if (output2 == null ? void 0 : output2[AstroJSX]) {
1854
+ if (output2?.[AstroJSX]) {
1812
1855
  renderResult = await renderJSXVNode(result, output2, skip);
1813
1856
  return renderResult;
1814
1857
  } else if (!output2) {
@@ -1910,76 +1953,9 @@ function filteredConsoleError(msg, ...rest) {
1910
1953
  originalConsoleError(msg, ...rest);
1911
1954
  }
1912
1955
 
1913
- const isNodeJS = typeof process === "object" && Object.prototype.toString.call(process) === "[object process]";
1914
- let StreamingCompatibleResponse;
1915
- function createResponseClass() {
1916
- StreamingCompatibleResponse = class extends Response {
1917
- #isStream;
1918
- #body;
1919
- constructor(body, init) {
1920
- let isStream = body instanceof ReadableStream;
1921
- super(isStream ? null : body, init);
1922
- this.#isStream = isStream;
1923
- this.#body = body;
1924
- }
1925
- get body() {
1926
- return this.#body;
1927
- }
1928
- async text() {
1929
- if (this.#isStream && isNodeJS) {
1930
- let decoder = new TextDecoder();
1931
- let body = this.#body;
1932
- let out = "";
1933
- for await (let chunk of streamAsyncIterator(body)) {
1934
- out += decoder.decode(chunk);
1935
- }
1936
- return out;
1937
- }
1938
- return super.text();
1939
- }
1940
- async arrayBuffer() {
1941
- if (this.#isStream && isNodeJS) {
1942
- let body = this.#body;
1943
- let chunks = [];
1944
- let len = 0;
1945
- for await (let chunk of streamAsyncIterator(body)) {
1946
- chunks.push(chunk);
1947
- len += chunk.length;
1948
- }
1949
- let ab = new Uint8Array(len);
1950
- let offset = 0;
1951
- for (const chunk of chunks) {
1952
- ab.set(chunk, offset);
1953
- offset += chunk.length;
1954
- }
1955
- return ab;
1956
- }
1957
- return super.arrayBuffer();
1958
- }
1959
- clone() {
1960
- return new StreamingCompatibleResponse(this.#body, {
1961
- status: this.status,
1962
- statusText: this.statusText,
1963
- headers: this.headers
1964
- });
1965
- }
1966
- };
1967
- return StreamingCompatibleResponse;
1968
- }
1969
- const createResponse = isNodeJS ? (body, init) => {
1970
- if (typeof body === "string" || ArrayBuffer.isView(body)) {
1971
- return new Response(body, init);
1972
- }
1973
- if (typeof StreamingCompatibleResponse === "undefined") {
1974
- return new (createResponseClass())(body, init);
1975
- }
1976
- return new StreamingCompatibleResponse(body, init);
1977
- } : (body, init) => new Response(body, init);
1978
-
1979
- async function renderPage$1(result, componentFactory, props, children, streaming, route) {
1980
- var _a, _b;
1956
+ async function renderPage(result, componentFactory, props, children, streaming, route) {
1981
1957
  if (!isAstroComponentFactory(componentFactory)) {
1982
- result._metadata.headInTree = ((_a = result.componentMetadata.get(componentFactory.moduleId)) == null ? void 0 : _a.containsHead) ?? false;
1958
+ result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
1983
1959
  const pageProps = { ...props ?? {}, "server:root": true };
1984
1960
  const str = await renderComponentToString(
1985
1961
  result,
@@ -1998,7 +1974,7 @@ async function renderPage$1(result, componentFactory, props, children, streaming
1998
1974
  ])
1999
1975
  });
2000
1976
  }
2001
- result._metadata.headInTree = ((_b = result.componentMetadata.get(componentFactory.moduleId)) == null ? void 0 : _b.containsHead) ?? false;
1977
+ result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
2002
1978
  let body;
2003
1979
  if (streaming) {
2004
1980
  body = await renderToReadableStream(result, componentFactory, props, children, true, route);
@@ -2013,7 +1989,7 @@ async function renderPage$1(result, componentFactory, props, children, streaming
2013
1989
  body = encoder.encode(body);
2014
1990
  headers.set("Content-Length", body.byteLength.toString());
2015
1991
  }
2016
- const response = createResponse(body, { ...init, headers });
1992
+ const response = new Response(body, { ...init, headers });
2017
1993
  return response;
2018
1994
  }
2019
1995
 
@@ -2034,1690 +2010,4 @@ function spreadAttributes(values = {}, _name, { class: scopedClassName } = {}) {
2034
2010
  return markHTMLString(output);
2035
2011
  }
2036
2012
 
2037
- const AstroJSX = "astro:jsx";
2038
- const Empty = Symbol("empty");
2039
- const toSlotName = (slotAttr) => slotAttr;
2040
- function isVNode(vnode) {
2041
- return vnode && typeof vnode === "object" && vnode[AstroJSX];
2042
- }
2043
- function transformSlots(vnode) {
2044
- if (typeof vnode.type === "string")
2045
- return vnode;
2046
- const slots = {};
2047
- if (isVNode(vnode.props.children)) {
2048
- const child = vnode.props.children;
2049
- if (!isVNode(child))
2050
- return;
2051
- if (!("slot" in child.props))
2052
- return;
2053
- const name = toSlotName(child.props.slot);
2054
- slots[name] = [child];
2055
- slots[name]["$$slot"] = true;
2056
- delete child.props.slot;
2057
- delete vnode.props.children;
2058
- }
2059
- if (Array.isArray(vnode.props.children)) {
2060
- vnode.props.children = vnode.props.children.map((child) => {
2061
- if (!isVNode(child))
2062
- return child;
2063
- if (!("slot" in child.props))
2064
- return child;
2065
- const name = toSlotName(child.props.slot);
2066
- if (Array.isArray(slots[name])) {
2067
- slots[name].push(child);
2068
- } else {
2069
- slots[name] = [child];
2070
- slots[name]["$$slot"] = true;
2071
- }
2072
- delete child.props.slot;
2073
- return Empty;
2074
- }).filter((v) => v !== Empty);
2075
- }
2076
- Object.assign(vnode.props, slots);
2077
- }
2078
- function markRawChildren(child) {
2079
- if (typeof child === "string")
2080
- return markHTMLString(child);
2081
- if (Array.isArray(child))
2082
- return child.map((c) => markRawChildren(c));
2083
- return child;
2084
- }
2085
- function transformSetDirectives(vnode) {
2086
- if (!("set:html" in vnode.props || "set:text" in vnode.props))
2087
- return;
2088
- if ("set:html" in vnode.props) {
2089
- const children = markRawChildren(vnode.props["set:html"]);
2090
- delete vnode.props["set:html"];
2091
- Object.assign(vnode.props, { children });
2092
- return;
2093
- }
2094
- if ("set:text" in vnode.props) {
2095
- const children = vnode.props["set:text"];
2096
- delete vnode.props["set:text"];
2097
- Object.assign(vnode.props, { children });
2098
- return;
2099
- }
2100
- }
2101
- function createVNode(type, props) {
2102
- const vnode = {
2103
- [Renderer]: "astro:jsx",
2104
- [AstroJSX]: true,
2105
- type,
2106
- props: props ?? {}
2107
- };
2108
- transformSetDirectives(vnode);
2109
- transformSlots(vnode);
2110
- return vnode;
2111
- }
2112
-
2113
- const slotName = (str) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase());
2114
- async function check(Component, props, { default: children = null, ...slotted } = {}) {
2115
- if (typeof Component !== "function")
2116
- return false;
2117
- const slots = {};
2118
- for (const [key, value] of Object.entries(slotted)) {
2119
- const name = slotName(key);
2120
- slots[name] = value;
2121
- }
2122
- try {
2123
- const result = await Component({ ...props, ...slots, children });
2124
- return result[AstroJSX];
2125
- } catch (e) {
2126
- const error = e;
2127
- if (Component[Symbol.for("mdx-component")]) {
2128
- throw createFormattedError({
2129
- message: error.message,
2130
- title: error.name,
2131
- hint: `This issue often occurs when your MDX component encounters runtime errors.`,
2132
- name: error.name,
2133
- stack: error.stack
2134
- });
2135
- }
2136
- }
2137
- return false;
2138
- }
2139
- async function renderToStaticMarkup(Component, props = {}, { default: children = null, ...slotted } = {}) {
2140
- const slots = {};
2141
- for (const [key, value] of Object.entries(slotted)) {
2142
- const name = slotName(key);
2143
- slots[name] = value;
2144
- }
2145
- const { result } = this;
2146
- const html = await renderJSX(result, createVNode(Component, { ...props, ...slots, children }));
2147
- return { html };
2148
- }
2149
- function createFormattedError({ message, name, stack, hint }) {
2150
- const error = new Error(message);
2151
- error.name = name;
2152
- error.stack = stack;
2153
- error.hint = hint;
2154
- return error;
2155
- }
2156
- var server_default = {
2157
- check,
2158
- renderToStaticMarkup
2159
- };
2160
-
2161
- function getRouteGenerator(segments, addTrailingSlash) {
2162
- const template = segments.map((segment) => {
2163
- return "/" + segment.map((part) => {
2164
- if (part.spread) {
2165
- return `:${part.content.slice(3)}(.*)?`;
2166
- } else if (part.dynamic) {
2167
- return `:${part.content}`;
2168
- } else {
2169
- return part.content.normalize().replace(/\?/g, "%3F").replace(/#/g, "%23").replace(/%5B/g, "[").replace(/%5D/g, "]").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2170
- }
2171
- }).join("");
2172
- }).join("");
2173
- let trailing = "";
2174
- if (addTrailingSlash === "always" && segments.length) {
2175
- trailing = "/";
2176
- }
2177
- const toPath = compile(template + trailing);
2178
- return toPath;
2179
- }
2180
-
2181
- function deserializeRouteData(rawRouteData) {
2182
- return {
2183
- route: rawRouteData.route,
2184
- type: rawRouteData.type,
2185
- pattern: new RegExp(rawRouteData.pattern),
2186
- params: rawRouteData.params,
2187
- component: rawRouteData.component,
2188
- generate: getRouteGenerator(rawRouteData.segments, rawRouteData._meta.trailingSlash),
2189
- pathname: rawRouteData.pathname || void 0,
2190
- segments: rawRouteData.segments,
2191
- prerender: rawRouteData.prerender,
2192
- redirect: rawRouteData.redirect,
2193
- redirectRoute: rawRouteData.redirectRoute ? deserializeRouteData(rawRouteData.redirectRoute) : void 0
2194
- };
2195
- }
2196
-
2197
- function deserializeManifest(serializedManifest) {
2198
- const routes = [];
2199
- for (const serializedRoute of serializedManifest.routes) {
2200
- routes.push({
2201
- ...serializedRoute,
2202
- routeData: deserializeRouteData(serializedRoute.routeData)
2203
- });
2204
- const route = serializedRoute;
2205
- route.routeData = deserializeRouteData(serializedRoute.routeData);
2206
- }
2207
- const assets = new Set(serializedManifest.assets);
2208
- const componentMetadata = new Map(serializedManifest.componentMetadata);
2209
- const clientDirectives = new Map(serializedManifest.clientDirectives);
2210
- return {
2211
- ...serializedManifest,
2212
- assets,
2213
- componentMetadata,
2214
- clientDirectives,
2215
- routes
2216
- };
2217
- }
2218
-
2219
- const DELETED_EXPIRATION = /* @__PURE__ */ new Date(0);
2220
- const DELETED_VALUE = "deleted";
2221
- const responseSentSymbol$2 = Symbol.for("astro.responseSent");
2222
- class AstroCookie {
2223
- constructor(value) {
2224
- this.value = value;
2225
- }
2226
- json() {
2227
- if (this.value === void 0) {
2228
- throw new Error(`Cannot convert undefined to an object.`);
2229
- }
2230
- return JSON.parse(this.value);
2231
- }
2232
- number() {
2233
- return Number(this.value);
2234
- }
2235
- boolean() {
2236
- if (this.value === "false")
2237
- return false;
2238
- if (this.value === "0")
2239
- return false;
2240
- return Boolean(this.value);
2241
- }
2242
- }
2243
- class AstroCookies {
2244
- #request;
2245
- #requestValues;
2246
- #outgoing;
2247
- constructor(request) {
2248
- this.#request = request;
2249
- this.#requestValues = null;
2250
- this.#outgoing = null;
2251
- }
2252
- /**
2253
- * Astro.cookies.delete(key) is used to delete a cookie. Using this method will result
2254
- * in a Set-Cookie header added to the response.
2255
- * @param key The cookie to delete
2256
- * @param options Options related to this deletion, such as the path of the cookie.
2257
- */
2258
- delete(key, options) {
2259
- const serializeOptions = {
2260
- expires: DELETED_EXPIRATION
2261
- };
2262
- if (options == null ? void 0 : options.domain) {
2263
- serializeOptions.domain = options.domain;
2264
- }
2265
- if (options == null ? void 0 : options.path) {
2266
- serializeOptions.path = options.path;
2267
- }
2268
- this.#ensureOutgoingMap().set(key, [
2269
- DELETED_VALUE,
2270
- serialize(key, DELETED_VALUE, serializeOptions),
2271
- false
2272
- ]);
2273
- }
2274
- /**
2275
- * Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the
2276
- * request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken
2277
- * from that set call, overriding any values already part of the request.
2278
- * @param key The cookie to get.
2279
- * @returns An object containing the cookie value as well as convenience methods for converting its value.
2280
- */
2281
- get(key) {
2282
- var _a;
2283
- if ((_a = this.#outgoing) == null ? void 0 : _a.has(key)) {
2284
- let [serializedValue, , isSetValue] = this.#outgoing.get(key);
2285
- if (isSetValue) {
2286
- return new AstroCookie(serializedValue);
2287
- } else {
2288
- return new AstroCookie(void 0);
2289
- }
2290
- }
2291
- const values = this.#ensureParsed();
2292
- const value = values[key];
2293
- return new AstroCookie(value);
2294
- }
2295
- /**
2296
- * Astro.cookies.has(key) returns a boolean indicating whether this cookie is either
2297
- * part of the initial request or set via Astro.cookies.set(key)
2298
- * @param key The cookie to check for.
2299
- * @returns
2300
- */
2301
- has(key) {
2302
- var _a;
2303
- if ((_a = this.#outgoing) == null ? void 0 : _a.has(key)) {
2304
- let [, , isSetValue] = this.#outgoing.get(key);
2305
- return isSetValue;
2306
- }
2307
- const values = this.#ensureParsed();
2308
- return !!values[key];
2309
- }
2310
- /**
2311
- * Astro.cookies.set(key, value) is used to set a cookie's value. If provided
2312
- * an object it will be stringified via JSON.stringify(value). Additionally you
2313
- * can provide options customizing how this cookie will be set, such as setting httpOnly
2314
- * in order to prevent the cookie from being read in client-side JavaScript.
2315
- * @param key The name of the cookie to set.
2316
- * @param value A value, either a string or other primitive or an object.
2317
- * @param options Options for the cookie, such as the path and security settings.
2318
- */
2319
- set(key, value, options) {
2320
- let serializedValue;
2321
- if (typeof value === "string") {
2322
- serializedValue = value;
2323
- } else {
2324
- let toStringValue = value.toString();
2325
- if (toStringValue === Object.prototype.toString.call(value)) {
2326
- serializedValue = JSON.stringify(value);
2327
- } else {
2328
- serializedValue = toStringValue;
2329
- }
2330
- }
2331
- const serializeOptions = {};
2332
- if (options) {
2333
- Object.assign(serializeOptions, options);
2334
- }
2335
- this.#ensureOutgoingMap().set(key, [
2336
- serializedValue,
2337
- serialize(key, serializedValue, serializeOptions),
2338
- true
2339
- ]);
2340
- if (this.#request[responseSentSymbol$2]) {
2341
- throw new AstroError({
2342
- ...ResponseSentError
2343
- });
2344
- }
2345
- }
2346
- /**
2347
- * Astro.cookies.header() returns an iterator for the cookies that have previously
2348
- * been set by either Astro.cookies.set() or Astro.cookies.delete().
2349
- * This method is primarily used by adapters to set the header on outgoing responses.
2350
- * @returns
2351
- */
2352
- *headers() {
2353
- if (this.#outgoing == null)
2354
- return;
2355
- for (const [, value] of this.#outgoing) {
2356
- yield value[1];
2357
- }
2358
- }
2359
- #ensureParsed() {
2360
- if (!this.#requestValues) {
2361
- this.#parse();
2362
- }
2363
- if (!this.#requestValues) {
2364
- this.#requestValues = {};
2365
- }
2366
- return this.#requestValues;
2367
- }
2368
- #ensureOutgoingMap() {
2369
- if (!this.#outgoing) {
2370
- this.#outgoing = /* @__PURE__ */ new Map();
2371
- }
2372
- return this.#outgoing;
2373
- }
2374
- #parse() {
2375
- const raw = this.#request.headers.get("cookie");
2376
- if (!raw) {
2377
- return;
2378
- }
2379
- this.#requestValues = parse(raw);
2380
- }
2381
- }
2382
-
2383
- const astroCookiesSymbol = Symbol.for("astro.cookies");
2384
- function attachToResponse(response, cookies) {
2385
- Reflect.set(response, astroCookiesSymbol, cookies);
2386
- }
2387
- function getFromResponse(response) {
2388
- let cookies = Reflect.get(response, astroCookiesSymbol);
2389
- if (cookies != null) {
2390
- return cookies;
2391
- } else {
2392
- return void 0;
2393
- }
2394
- }
2395
- function* getSetCookiesFromResponse(response) {
2396
- const cookies = getFromResponse(response);
2397
- if (!cookies) {
2398
- return [];
2399
- }
2400
- for (const headerValue of cookies.headers()) {
2401
- yield headerValue;
2402
- }
2403
- return [];
2404
- }
2405
-
2406
- const dateTimeFormat = new Intl.DateTimeFormat([], {
2407
- hour: "2-digit",
2408
- minute: "2-digit",
2409
- second: "2-digit"
2410
- });
2411
- const levels = {
2412
- debug: 20,
2413
- info: 30,
2414
- warn: 40,
2415
- error: 50,
2416
- silent: 90
2417
- };
2418
- function log(opts, level, type, message) {
2419
- const logLevel = opts.level;
2420
- const dest = opts.dest;
2421
- const event = {
2422
- type,
2423
- level,
2424
- message
2425
- };
2426
- if (levels[logLevel] > levels[level]) {
2427
- return;
2428
- }
2429
- dest.write(event);
2430
- }
2431
- function warn(opts, type, message) {
2432
- return log(opts, "warn", type, message);
2433
- }
2434
- function error(opts, type, message) {
2435
- return log(opts, "error", type, message);
2436
- }
2437
- function debug(...args) {
2438
- if ("_astroGlobalDebug" in globalThis) {
2439
- globalThis._astroGlobalDebug(...args);
2440
- }
2441
- }
2442
- if (typeof process !== "undefined") {
2443
- let proc = process;
2444
- if ("argv" in proc && Array.isArray(proc.argv)) {
2445
- if (proc.argv.includes("--verbose")) ; else if (proc.argv.includes("--silent")) ; else ;
2446
- }
2447
- }
2448
-
2449
- let lastMessage;
2450
- let lastMessageCount = 1;
2451
- const consoleLogDestination = {
2452
- write(event) {
2453
- let dest = console.error;
2454
- if (levels[event.level] < levels["error"]) {
2455
- dest = console.log;
2456
- }
2457
- function getPrefix() {
2458
- let prefix = "";
2459
- let type = event.type;
2460
- if (type) {
2461
- prefix += dim(dateTimeFormat.format(/* @__PURE__ */ new Date()) + " ");
2462
- if (event.level === "info") {
2463
- type = bold(cyan(`[${type}]`));
2464
- } else if (event.level === "warn") {
2465
- type = bold(yellow(`[${type}]`));
2466
- } else if (event.level === "error") {
2467
- type = bold(red(`[${type}]`));
2468
- }
2469
- prefix += `${type} `;
2470
- }
2471
- return reset(prefix);
2472
- }
2473
- let message = event.message;
2474
- if (message === lastMessage) {
2475
- lastMessageCount++;
2476
- message = `${message} ${yellow(`(x${lastMessageCount})`)}`;
2477
- } else {
2478
- lastMessage = message;
2479
- lastMessageCount = 1;
2480
- }
2481
- const outMessage = getPrefix() + message;
2482
- dest(outMessage);
2483
- return true;
2484
- }
2485
- };
2486
-
2487
- const RedirectComponentInstance = {
2488
- default() {
2489
- return new Response(null, {
2490
- status: 301
2491
- });
2492
- }
2493
- };
2494
- const RedirectSinglePageBuiltModule = {
2495
- page: () => Promise.resolve(RedirectComponentInstance),
2496
- onRequest: (ctx, next) => next(),
2497
- renderers: []
2498
- };
2499
-
2500
- function routeIsRedirect(route) {
2501
- return (route == null ? void 0 : route.type) === "redirect";
2502
- }
2503
- function redirectRouteGenerate(redirectRoute, data) {
2504
- const routeData = redirectRoute.redirectRoute;
2505
- const route = redirectRoute.redirect;
2506
- if (typeof routeData !== "undefined") {
2507
- return (routeData == null ? void 0 : routeData.generate(data)) || (routeData == null ? void 0 : routeData.pathname) || "/";
2508
- } else if (typeof route === "string") {
2509
- return route;
2510
- } else if (typeof route === "undefined") {
2511
- return "/";
2512
- }
2513
- return route.destination;
2514
- }
2515
- function redirectRouteStatus(redirectRoute, method = "GET") {
2516
- const routeData = redirectRoute.redirectRoute;
2517
- if (typeof (routeData == null ? void 0 : routeData.redirect) === "object") {
2518
- return routeData.redirect.status;
2519
- } else if (method !== "GET") {
2520
- return 308;
2521
- }
2522
- return 301;
2523
- }
2524
-
2525
- async function callMiddleware(logging, onRequest, apiContext, responseFunction) {
2526
- let nextCalled = false;
2527
- let responseFunctionPromise = void 0;
2528
- const next = async () => {
2529
- nextCalled = true;
2530
- responseFunctionPromise = responseFunction();
2531
- return responseFunctionPromise;
2532
- };
2533
- let middlewarePromise = onRequest(apiContext, next);
2534
- return await Promise.resolve(middlewarePromise).then(async (value) => {
2535
- if (isEndpointOutput(value)) {
2536
- warn(
2537
- logging,
2538
- "middleware",
2539
- `Using simple endpoints can cause unexpected issues in the chain of middleware functions.
2540
- It's strongly suggested to use full ${bold("Response")} objects.`
2541
- );
2542
- }
2543
- if (nextCalled) {
2544
- if (typeof value !== "undefined") {
2545
- if (value instanceof Response === false) {
2546
- throw new AstroError(MiddlewareNotAResponse);
2547
- }
2548
- return value;
2549
- } else {
2550
- if (responseFunctionPromise) {
2551
- return responseFunctionPromise;
2552
- } else {
2553
- throw new AstroError(MiddlewareNotAResponse);
2554
- }
2555
- }
2556
- } else if (typeof value === "undefined") {
2557
- throw new AstroError(MiddlewareNoDataOrNextCalled);
2558
- } else if (value instanceof Response === false) {
2559
- throw new AstroError(MiddlewareNotAResponse);
2560
- } else {
2561
- return value;
2562
- }
2563
- });
2564
- }
2565
- function isEndpointOutput(endpointResult) {
2566
- return !(endpointResult instanceof Response) && typeof endpointResult === "object" && typeof endpointResult.body === "string";
2567
- }
2568
-
2569
- const clientAddressSymbol$2 = Symbol.for("astro.clientAddress");
2570
- const clientLocalsSymbol$2 = Symbol.for("astro.locals");
2571
- function createAPIContext({
2572
- request,
2573
- params,
2574
- site,
2575
- props,
2576
- adapterName
2577
- }) {
2578
- const context = {
2579
- cookies: new AstroCookies(request),
2580
- request,
2581
- params,
2582
- site: site ? new URL(site) : void 0,
2583
- generator: `Astro v${ASTRO_VERSION}`,
2584
- props,
2585
- redirect(path, status) {
2586
- return new Response(null, {
2587
- status: status || 302,
2588
- headers: {
2589
- Location: path
2590
- }
2591
- });
2592
- },
2593
- url: new URL(request.url),
2594
- get clientAddress() {
2595
- if (!(clientAddressSymbol$2 in request)) {
2596
- if (adapterName) {
2597
- throw new AstroError({
2598
- ...ClientAddressNotAvailable,
2599
- message: ClientAddressNotAvailable.message(adapterName)
2600
- });
2601
- } else {
2602
- throw new AstroError(StaticClientAddressNotAvailable);
2603
- }
2604
- }
2605
- return Reflect.get(request, clientAddressSymbol$2);
2606
- }
2607
- };
2608
- Object.defineProperty(context, "locals", {
2609
- enumerable: true,
2610
- get() {
2611
- return Reflect.get(request, clientLocalsSymbol$2);
2612
- },
2613
- set(val) {
2614
- if (typeof val !== "object") {
2615
- throw new AstroError(LocalsNotAnObject);
2616
- } else {
2617
- Reflect.set(request, clientLocalsSymbol$2, val);
2618
- }
2619
- }
2620
- });
2621
- return context;
2622
- }
2623
- async function callEndpoint(mod, env, ctx, onRequest) {
2624
- var _a;
2625
- const context = createAPIContext({
2626
- request: ctx.request,
2627
- params: ctx.params,
2628
- props: ctx.props,
2629
- site: env.site,
2630
- adapterName: env.adapterName
2631
- });
2632
- let response;
2633
- if (onRequest) {
2634
- response = await callMiddleware(
2635
- env.logging,
2636
- onRequest,
2637
- context,
2638
- async () => {
2639
- return await renderEndpoint(mod, context, env.ssr);
2640
- }
2641
- );
2642
- } else {
2643
- response = await renderEndpoint(mod, context, env.ssr);
2644
- }
2645
- if (response instanceof Response) {
2646
- attachToResponse(response, context.cookies);
2647
- return {
2648
- type: "response",
2649
- response
2650
- };
2651
- }
2652
- if (env.ssr && !((_a = ctx.route) == null ? void 0 : _a.prerender)) {
2653
- if (response.hasOwnProperty("headers")) {
2654
- warn(
2655
- env.logging,
2656
- "ssr",
2657
- "Setting headers is not supported when returning an object. Please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information."
2658
- );
2659
- }
2660
- if (response.encoding) {
2661
- warn(
2662
- env.logging,
2663
- "ssr",
2664
- "`encoding` is ignored in SSR. To return a charset other than UTF-8, please return an instance of Response. See https://docs.astro.build/en/core-concepts/endpoints/#server-endpoints-api-routes for more information."
2665
- );
2666
- }
2667
- }
2668
- return {
2669
- ...response,
2670
- type: "simple",
2671
- cookies: context.cookies
2672
- };
2673
- }
2674
-
2675
- const clientAddressSymbol$1 = Symbol.for("astro.clientAddress");
2676
- const responseSentSymbol$1 = Symbol.for("astro.responseSent");
2677
- function getFunctionExpression(slot) {
2678
- var _a;
2679
- if (!slot)
2680
- return;
2681
- if (((_a = slot.expressions) == null ? void 0 : _a.length) !== 1)
2682
- return;
2683
- return slot.expressions[0];
2684
- }
2685
- class Slots {
2686
- #result;
2687
- #slots;
2688
- #loggingOpts;
2689
- constructor(result, slots, logging) {
2690
- this.#result = result;
2691
- this.#slots = slots;
2692
- this.#loggingOpts = logging;
2693
- if (slots) {
2694
- for (const key of Object.keys(slots)) {
2695
- if (this[key] !== void 0) {
2696
- throw new AstroError({
2697
- ...ReservedSlotName,
2698
- message: ReservedSlotName.message(key)
2699
- });
2700
- }
2701
- Object.defineProperty(this, key, {
2702
- get() {
2703
- return true;
2704
- },
2705
- enumerable: true
2706
- });
2707
- }
2708
- }
2709
- }
2710
- has(name) {
2711
- if (!this.#slots)
2712
- return false;
2713
- return Boolean(this.#slots[name]);
2714
- }
2715
- async render(name, args = []) {
2716
- if (!this.#slots || !this.has(name))
2717
- return;
2718
- const result = this.#result;
2719
- if (!Array.isArray(args)) {
2720
- warn(
2721
- this.#loggingOpts,
2722
- "Astro.slots.render",
2723
- `Expected second parameter to be an array, received a ${typeof args}. If you're trying to pass an array as a single argument and getting unexpected results, make sure you're passing your array as a item of an array. Ex: Astro.slots.render('default', [["Hello", "World"]])`
2724
- );
2725
- } else if (args.length > 0) {
2726
- const slotValue = this.#slots[name];
2727
- const component = typeof slotValue === "function" ? await slotValue(result) : await slotValue;
2728
- const expression = getFunctionExpression(component);
2729
- if (expression) {
2730
- const slot = async () => typeof expression === "function" ? expression(...args) : expression;
2731
- return await renderSlotToString(result, slot).then((res) => {
2732
- return res != null ? String(res) : res;
2733
- });
2734
- }
2735
- if (typeof component === "function") {
2736
- return await renderJSX(result, component(...args)).then(
2737
- (res) => res != null ? String(res) : res
2738
- );
2739
- }
2740
- }
2741
- const content = await renderSlotToString(result, this.#slots[name]);
2742
- const outHTML = chunkToString(result, content);
2743
- return outHTML;
2744
- }
2745
- }
2746
- let renderMarkdown = null;
2747
- function createResult(args) {
2748
- const { markdown, params, request, resolve, locals } = args;
2749
- const url = new URL(request.url);
2750
- const headers = new Headers();
2751
- headers.set("Content-Type", "text/html");
2752
- const response = {
2753
- status: args.status,
2754
- statusText: "OK",
2755
- headers
2756
- };
2757
- Object.defineProperty(response, "headers", {
2758
- value: response.headers,
2759
- enumerable: true,
2760
- writable: false
2761
- });
2762
- let cookies = args.cookies;
2763
- const result = {
2764
- styles: args.styles ?? /* @__PURE__ */ new Set(),
2765
- scripts: args.scripts ?? /* @__PURE__ */ new Set(),
2766
- links: args.links ?? /* @__PURE__ */ new Set(),
2767
- componentMetadata: args.componentMetadata ?? /* @__PURE__ */ new Map(),
2768
- renderers: args.renderers,
2769
- clientDirectives: args.clientDirectives,
2770
- compressHTML: args.compressHTML,
2771
- pathname: args.pathname,
2772
- cookies,
2773
- /** This function returns the `Astro` faux-global */
2774
- createAstro(astroGlobal, props, slots) {
2775
- const astroSlots = new Slots(result, slots, args.logging);
2776
- const Astro = {
2777
- // @ts-expect-error
2778
- __proto__: astroGlobal,
2779
- get clientAddress() {
2780
- if (!(clientAddressSymbol$1 in request)) {
2781
- if (args.adapterName) {
2782
- throw new AstroError({
2783
- ...ClientAddressNotAvailable,
2784
- message: ClientAddressNotAvailable.message(args.adapterName)
2785
- });
2786
- } else {
2787
- throw new AstroError(StaticClientAddressNotAvailable);
2788
- }
2789
- }
2790
- return Reflect.get(request, clientAddressSymbol$1);
2791
- },
2792
- get cookies() {
2793
- if (cookies) {
2794
- return cookies;
2795
- }
2796
- cookies = new AstroCookies(request);
2797
- result.cookies = cookies;
2798
- return cookies;
2799
- },
2800
- params,
2801
- props,
2802
- locals,
2803
- request,
2804
- url,
2805
- redirect(path, status) {
2806
- if (request[responseSentSymbol$1]) {
2807
- throw new AstroError({
2808
- ...ResponseSentError
2809
- });
2810
- }
2811
- return new Response(null, {
2812
- status: status || 302,
2813
- headers: {
2814
- Location: path
2815
- }
2816
- });
2817
- },
2818
- response,
2819
- slots: astroSlots
2820
- };
2821
- Object.defineProperty(Astro, "__renderMarkdown", {
2822
- // Ensure this API is not exposed to users
2823
- enumerable: false,
2824
- writable: false,
2825
- // TODO: Remove this hole "Deno" logic once our plugin gets Deno support
2826
- value: async function(content, opts) {
2827
- if (typeof Deno !== "undefined") {
2828
- throw new Error("Markdown is not supported in Deno SSR");
2829
- }
2830
- if (!renderMarkdown) {
2831
- let astroRemark = "@astrojs/";
2832
- astroRemark += "markdown-remark";
2833
- renderMarkdown = (await import(astroRemark)).renderMarkdown;
2834
- }
2835
- const { code } = await renderMarkdown(content, { ...markdown, ...opts ?? {} });
2836
- return code;
2837
- }
2838
- });
2839
- return Astro;
2840
- },
2841
- resolve,
2842
- response,
2843
- _metadata: {
2844
- hasHydrationScript: false,
2845
- hasRenderedHead: false,
2846
- hasDirectives: /* @__PURE__ */ new Set(),
2847
- headInTree: false,
2848
- extraHead: [],
2849
- propagators: /* @__PURE__ */ new Map()
2850
- }
2851
- };
2852
- return result;
2853
- }
2854
-
2855
- async function renderPage({ mod, renderContext, env, cookies }) {
2856
- if (routeIsRedirect(renderContext.route)) {
2857
- return new Response(null, {
2858
- status: redirectRouteStatus(renderContext.route, renderContext.request.method),
2859
- headers: {
2860
- location: redirectRouteGenerate(renderContext.route, renderContext.params)
2861
- }
2862
- });
2863
- }
2864
- const Component = mod.default;
2865
- if (!Component)
2866
- throw new Error(`Expected an exported Astro component but received typeof ${typeof Component}`);
2867
- const result = createResult({
2868
- adapterName: env.adapterName,
2869
- links: renderContext.links,
2870
- styles: renderContext.styles,
2871
- logging: env.logging,
2872
- markdown: env.markdown,
2873
- params: renderContext.params,
2874
- pathname: renderContext.pathname,
2875
- componentMetadata: renderContext.componentMetadata,
2876
- resolve: env.resolve,
2877
- renderers: env.renderers,
2878
- clientDirectives: env.clientDirectives,
2879
- compressHTML: env.compressHTML,
2880
- request: renderContext.request,
2881
- site: env.site,
2882
- scripts: renderContext.scripts,
2883
- ssr: env.ssr,
2884
- status: renderContext.status ?? 200,
2885
- cookies,
2886
- locals: renderContext.locals ?? {}
2887
- });
2888
- if (typeof mod.components === "object") {
2889
- Object.assign(renderContext.props, { components: mod.components });
2890
- }
2891
- let response = await renderPage$1(
2892
- result,
2893
- Component,
2894
- renderContext.props,
2895
- null,
2896
- env.streaming,
2897
- renderContext.route
2898
- );
2899
- if (result.cookies) {
2900
- attachToResponse(response, result.cookies);
2901
- }
2902
- return response;
2903
- }
2904
- async function tryRenderRoute(routeType, renderContext, env, mod, onRequest) {
2905
- const apiContext = createAPIContext({
2906
- request: renderContext.request,
2907
- params: renderContext.params,
2908
- props: renderContext.props,
2909
- site: env.site,
2910
- adapterName: env.adapterName
2911
- });
2912
- switch (routeType) {
2913
- case "page":
2914
- case "redirect": {
2915
- if (onRequest) {
2916
- return await callMiddleware(
2917
- env.logging,
2918
- onRequest,
2919
- apiContext,
2920
- () => {
2921
- return renderPage({
2922
- mod,
2923
- renderContext,
2924
- env,
2925
- cookies: apiContext.cookies
2926
- });
2927
- }
2928
- );
2929
- } else {
2930
- return await renderPage({
2931
- mod,
2932
- renderContext,
2933
- env,
2934
- cookies: apiContext.cookies
2935
- });
2936
- }
2937
- }
2938
- case "endpoint": {
2939
- const result = await callEndpoint(
2940
- mod,
2941
- env,
2942
- renderContext,
2943
- onRequest
2944
- );
2945
- return result;
2946
- }
2947
- default:
2948
- throw new Error(`Couldn't find route of type [${routeType}]`);
2949
- }
2950
- }
2951
- function isResponse(result, routeType) {
2952
- return result instanceof Response && (routeType === "page" || routeType === "redirect");
2953
- }
2954
-
2955
- const VALID_PARAM_TYPES = ["string", "number", "undefined"];
2956
- function validateGetStaticPathsParameter([key, value], route) {
2957
- if (!VALID_PARAM_TYPES.includes(typeof value)) {
2958
- throw new AstroError({
2959
- ...GetStaticPathsInvalidRouteParam,
2960
- message: GetStaticPathsInvalidRouteParam.message(key, value, typeof value),
2961
- location: {
2962
- file: route
2963
- }
2964
- });
2965
- }
2966
- }
2967
- function validateDynamicRouteModule(mod, {
2968
- ssr,
2969
- route
2970
- }) {
2971
- if ((!ssr || route.prerender) && !mod.getStaticPaths) {
2972
- throw new AstroError({
2973
- ...GetStaticPathsRequired,
2974
- location: { file: route.component }
2975
- });
2976
- }
2977
- }
2978
- function validateGetStaticPathsResult(result, logging, route) {
2979
- if (!Array.isArray(result)) {
2980
- throw new AstroError({
2981
- ...InvalidGetStaticPathsReturn,
2982
- message: InvalidGetStaticPathsReturn.message(typeof result),
2983
- location: {
2984
- file: route.component
2985
- }
2986
- });
2987
- }
2988
- result.forEach((pathObject) => {
2989
- if (pathObject.params === void 0 || pathObject.params === null || pathObject.params && Object.keys(pathObject.params).length === 0) {
2990
- throw new AstroError({
2991
- ...GetStaticPathsExpectedParams,
2992
- location: {
2993
- file: route.component
2994
- }
2995
- });
2996
- }
2997
- if (typeof pathObject.params !== "object") {
2998
- throw new AstroError({
2999
- ...InvalidGetStaticPathParam,
3000
- message: InvalidGetStaticPathParam.message(typeof pathObject.params),
3001
- location: {
3002
- file: route.component
3003
- }
3004
- });
3005
- }
3006
- for (const [key, val] of Object.entries(pathObject.params)) {
3007
- if (!(typeof val === "undefined" || typeof val === "string" || typeof val === "number")) {
3008
- warn(
3009
- logging,
3010
- "getStaticPaths",
3011
- `invalid path param: ${key}. A string, number or undefined value was expected, but got \`${JSON.stringify(
3012
- val
3013
- )}\`.`
3014
- );
3015
- }
3016
- if (typeof val === "string" && val === "") {
3017
- warn(
3018
- logging,
3019
- "getStaticPaths",
3020
- `invalid path param: ${key}. \`undefined\` expected for an optional param, but got empty string.`
3021
- );
3022
- }
3023
- }
3024
- });
3025
- }
3026
-
3027
- function getParams(array) {
3028
- const fn = (match) => {
3029
- const params = {};
3030
- array.forEach((key, i) => {
3031
- if (key.startsWith("...")) {
3032
- params[key.slice(3)] = match[i + 1] ? decodeURIComponent(match[i + 1]) : void 0;
3033
- } else {
3034
- params[key] = decodeURIComponent(match[i + 1]);
3035
- }
3036
- });
3037
- return params;
3038
- };
3039
- return fn;
3040
- }
3041
- function stringifyParams(params, route) {
3042
- const validatedParams = Object.entries(params).reduce((acc, next) => {
3043
- validateGetStaticPathsParameter(next, route.component);
3044
- const [key, value] = next;
3045
- acc[key] = value == null ? void 0 : value.toString();
3046
- return acc;
3047
- }, {});
3048
- return JSON.stringify(route.generate(validatedParams));
3049
- }
3050
-
3051
- function generatePaginateFunction(routeMatch) {
3052
- return function paginateUtility(data, args = {}) {
3053
- let { pageSize: _pageSize, params: _params, props: _props } = args;
3054
- const pageSize = _pageSize || 10;
3055
- const paramName = "page";
3056
- const additionalParams = _params || {};
3057
- const additionalProps = _props || {};
3058
- let includesFirstPageNumber;
3059
- if (routeMatch.params.includes(`...${paramName}`)) {
3060
- includesFirstPageNumber = false;
3061
- } else if (routeMatch.params.includes(`${paramName}`)) {
3062
- includesFirstPageNumber = true;
3063
- } else {
3064
- throw new AstroError({
3065
- ...PageNumberParamNotFound,
3066
- message: PageNumberParamNotFound.message(paramName)
3067
- });
3068
- }
3069
- const lastPage = Math.max(1, Math.ceil(data.length / pageSize));
3070
- const result = [...Array(lastPage).keys()].map((num) => {
3071
- const pageNum = num + 1;
3072
- const start = pageSize === Infinity ? 0 : (pageNum - 1) * pageSize;
3073
- const end = Math.min(start + pageSize, data.length);
3074
- const params = {
3075
- ...additionalParams,
3076
- [paramName]: includesFirstPageNumber || pageNum > 1 ? String(pageNum) : void 0
3077
- };
3078
- const current = correctIndexRoute(routeMatch.generate({ ...params }));
3079
- const next = pageNum === lastPage ? void 0 : correctIndexRoute(routeMatch.generate({ ...params, page: String(pageNum + 1) }));
3080
- const prev = pageNum === 1 ? void 0 : correctIndexRoute(
3081
- routeMatch.generate({
3082
- ...params,
3083
- page: !includesFirstPageNumber && pageNum - 1 === 1 ? void 0 : String(pageNum - 1)
3084
- })
3085
- );
3086
- return {
3087
- params,
3088
- props: {
3089
- ...additionalProps,
3090
- page: {
3091
- data: data.slice(start, end),
3092
- start,
3093
- end: end - 1,
3094
- size: pageSize,
3095
- total: data.length,
3096
- currentPage: pageNum,
3097
- lastPage,
3098
- url: { current, next, prev }
3099
- }
3100
- }
3101
- };
3102
- });
3103
- return result;
3104
- };
3105
- }
3106
- function correctIndexRoute(route) {
3107
- if (route === "") {
3108
- return "/";
3109
- }
3110
- return route;
3111
- }
3112
-
3113
- async function callGetStaticPaths({
3114
- mod,
3115
- route,
3116
- routeCache,
3117
- isValidate,
3118
- logging,
3119
- ssr
3120
- }) {
3121
- const cached = routeCache.get(route);
3122
- if (cached == null ? void 0 : cached.staticPaths)
3123
- return cached.staticPaths;
3124
- validateDynamicRouteModule(mod, { ssr, route });
3125
- if (ssr && !route.prerender) {
3126
- const entry = Object.assign([], { keyed: /* @__PURE__ */ new Map() });
3127
- routeCache.set(route, { ...cached, staticPaths: entry });
3128
- return entry;
3129
- }
3130
- if (!mod.getStaticPaths) {
3131
- throw new Error("Unexpected Error.");
3132
- }
3133
- let staticPaths = [];
3134
- staticPaths = await mod.getStaticPaths({
3135
- paginate: generatePaginateFunction(route),
3136
- rss() {
3137
- throw new AstroError(GetStaticPathsRemovedRSSHelper);
3138
- }
3139
- });
3140
- if (Array.isArray(staticPaths)) {
3141
- staticPaths = staticPaths.flat();
3142
- }
3143
- if (isValidate) {
3144
- validateGetStaticPathsResult(staticPaths, logging, route);
3145
- }
3146
- const keyedStaticPaths = staticPaths;
3147
- keyedStaticPaths.keyed = /* @__PURE__ */ new Map();
3148
- for (const sp of keyedStaticPaths) {
3149
- const paramsKey = stringifyParams(sp.params, route);
3150
- keyedStaticPaths.keyed.set(paramsKey, sp);
3151
- }
3152
- routeCache.set(route, { ...cached, staticPaths: keyedStaticPaths });
3153
- return keyedStaticPaths;
3154
- }
3155
- class RouteCache {
3156
- constructor(logging, mode = "production") {
3157
- this.cache = {};
3158
- this.logging = logging;
3159
- this.mode = mode;
3160
- }
3161
- /** Clear the cache. */
3162
- clearAll() {
3163
- this.cache = {};
3164
- }
3165
- set(route, entry) {
3166
- var _a;
3167
- if (this.mode === "production" && ((_a = this.cache[route.component]) == null ? void 0 : _a.staticPaths)) {
3168
- warn(
3169
- this.logging,
3170
- "routeCache",
3171
- `Internal Warning: route cache overwritten. (${route.component})`
3172
- );
3173
- }
3174
- this.cache[route.component] = entry;
3175
- }
3176
- get(route) {
3177
- return this.cache[route.component];
3178
- }
3179
- }
3180
- function findPathItemByKey(staticPaths, params, route) {
3181
- const paramsKey = stringifyParams(params, route);
3182
- const matchedStaticPath = staticPaths.keyed.get(paramsKey);
3183
- if (matchedStaticPath) {
3184
- return matchedStaticPath;
3185
- }
3186
- debug("findPathItemByKey", `Unexpected cache miss looking for ${paramsKey}`);
3187
- }
3188
-
3189
- async function getParamsAndProps(opts) {
3190
- const { logging, mod, route, routeCache, pathname, ssr } = opts;
3191
- if (!route || route.pathname) {
3192
- return [{}, {}];
3193
- }
3194
- const params = getRouteParams(route, pathname) ?? {};
3195
- validatePrerenderEndpointCollision(route, mod, params);
3196
- const staticPaths = await callGetStaticPaths({
3197
- mod,
3198
- route,
3199
- routeCache,
3200
- isValidate: true,
3201
- logging,
3202
- ssr
3203
- });
3204
- const matchedStaticPath = findPathItemByKey(staticPaths, params, route);
3205
- if (!matchedStaticPath && (ssr ? route.prerender : true)) {
3206
- throw new AstroError({
3207
- ...NoMatchingStaticPathFound,
3208
- message: NoMatchingStaticPathFound.message(pathname),
3209
- hint: NoMatchingStaticPathFound.hint([route.component])
3210
- });
3211
- }
3212
- const props = (matchedStaticPath == null ? void 0 : matchedStaticPath.props) ? { ...matchedStaticPath.props } : {};
3213
- return [params, props];
3214
- }
3215
- function getRouteParams(route, pathname) {
3216
- if (route.params.length) {
3217
- const paramsMatch = route.pattern.exec(decodeURIComponent(pathname));
3218
- if (paramsMatch) {
3219
- return getParams(route.params)(paramsMatch);
3220
- }
3221
- }
3222
- }
3223
- function validatePrerenderEndpointCollision(route, mod, params) {
3224
- if (route.type === "endpoint" && mod.getStaticPaths) {
3225
- const lastSegment = route.segments[route.segments.length - 1];
3226
- const paramValues = Object.values(params);
3227
- const lastParam = paramValues[paramValues.length - 1];
3228
- if (lastSegment.length === 1 && lastSegment[0].dynamic && lastParam === void 0) {
3229
- throw new AstroError({
3230
- ...PrerenderDynamicEndpointPathCollide,
3231
- message: PrerenderDynamicEndpointPathCollide.message(route.route),
3232
- hint: PrerenderDynamicEndpointPathCollide.hint(route.component),
3233
- location: {
3234
- file: route.component
3235
- }
3236
- });
3237
- }
3238
- }
3239
- }
3240
-
3241
- const clientLocalsSymbol$1 = Symbol.for("astro.locals");
3242
- async function createRenderContext(options) {
3243
- const request = options.request;
3244
- const pathname = options.pathname ?? new URL(request.url).pathname;
3245
- const [params, props] = await getParamsAndProps({
3246
- mod: options.mod,
3247
- route: options.route,
3248
- routeCache: options.env.routeCache,
3249
- pathname,
3250
- logging: options.env.logging,
3251
- ssr: options.env.ssr
3252
- });
3253
- const context = {
3254
- ...options,
3255
- pathname,
3256
- params,
3257
- props
3258
- };
3259
- Object.defineProperty(context, "locals", {
3260
- enumerable: true,
3261
- get() {
3262
- return Reflect.get(request, clientLocalsSymbol$1);
3263
- },
3264
- set(val) {
3265
- if (typeof val !== "object") {
3266
- throw new AstroError(LocalsNotAnObject);
3267
- } else {
3268
- Reflect.set(request, clientLocalsSymbol$1, val);
3269
- }
3270
- }
3271
- });
3272
- return context;
3273
- }
3274
-
3275
- function createEnvironment(options) {
3276
- return options;
3277
- }
3278
-
3279
- function createAssetLink(href, base, assetsPrefix) {
3280
- if (assetsPrefix) {
3281
- return joinPaths(assetsPrefix, slash(href));
3282
- } else if (base) {
3283
- return prependForwardSlash(joinPaths(base, slash(href)));
3284
- } else {
3285
- return href;
3286
- }
3287
- }
3288
- function createStylesheetElement(stylesheet, base, assetsPrefix) {
3289
- if (stylesheet.type === "inline") {
3290
- return {
3291
- props: {
3292
- type: "text/css"
3293
- },
3294
- children: stylesheet.content
3295
- };
3296
- } else {
3297
- return {
3298
- props: {
3299
- rel: "stylesheet",
3300
- href: createAssetLink(stylesheet.src, base, assetsPrefix)
3301
- },
3302
- children: ""
3303
- };
3304
- }
3305
- }
3306
- function createStylesheetElementSet(stylesheets, base, assetsPrefix) {
3307
- return new Set(stylesheets.map((s) => createStylesheetElement(s, base, assetsPrefix)));
3308
- }
3309
- function createModuleScriptElement(script, base, assetsPrefix) {
3310
- if (script.type === "external") {
3311
- return createModuleScriptElementWithSrc(script.value, base, assetsPrefix);
3312
- } else {
3313
- return {
3314
- props: {
3315
- type: "module"
3316
- },
3317
- children: script.value
3318
- };
3319
- }
3320
- }
3321
- function createModuleScriptElementWithSrc(src, base, assetsPrefix) {
3322
- return {
3323
- props: {
3324
- type: "module",
3325
- src: createAssetLink(src, base, assetsPrefix)
3326
- },
3327
- children: ""
3328
- };
3329
- }
3330
-
3331
- function matchRoute(pathname, manifest) {
3332
- return manifest.routes.find((route) => route.pattern.test(decodeURI(pathname)));
3333
- }
3334
-
3335
- const clientLocalsSymbol = Symbol.for("astro.locals");
3336
- const responseSentSymbol = Symbol.for("astro.responseSent");
3337
- const STATUS_CODES = /* @__PURE__ */ new Set([404, 500]);
3338
- class App {
3339
- /**
3340
- * The current environment of the application
3341
- */
3342
- #env;
3343
- #manifest;
3344
- #manifestData;
3345
- #routeDataToRouteInfo;
3346
- #encoder = new TextEncoder();
3347
- #logging = {
3348
- dest: consoleLogDestination,
3349
- level: "info"
3350
- };
3351
- #baseWithoutTrailingSlash;
3352
- constructor(manifest, streaming = true) {
3353
- this.#manifest = manifest;
3354
- this.#manifestData = {
3355
- routes: manifest.routes.map((route) => route.routeData)
3356
- };
3357
- this.#routeDataToRouteInfo = new Map(manifest.routes.map((route) => [route.routeData, route]));
3358
- this.#baseWithoutTrailingSlash = removeTrailingForwardSlash(this.#manifest.base);
3359
- this.#env = this.#createEnvironment(streaming);
3360
- }
3361
- set setManifest(newManifest) {
3362
- this.#manifest = newManifest;
3363
- }
3364
- /**
3365
- * Creates an environment by reading the stored manifest
3366
- *
3367
- * @param streaming
3368
- * @private
3369
- */
3370
- #createEnvironment(streaming = false) {
3371
- return createEnvironment({
3372
- adapterName: this.#manifest.adapterName,
3373
- logging: this.#logging,
3374
- markdown: this.#manifest.markdown,
3375
- mode: "production",
3376
- compressHTML: this.#manifest.compressHTML,
3377
- renderers: this.#manifest.renderers,
3378
- clientDirectives: this.#manifest.clientDirectives,
3379
- resolve: async (specifier) => {
3380
- if (!(specifier in this.#manifest.entryModules)) {
3381
- throw new Error(`Unable to resolve [${specifier}]`);
3382
- }
3383
- const bundlePath = this.#manifest.entryModules[specifier];
3384
- switch (true) {
3385
- case bundlePath.startsWith("data:"):
3386
- case bundlePath.length === 0: {
3387
- return bundlePath;
3388
- }
3389
- default: {
3390
- return createAssetLink(bundlePath, this.#manifest.base, this.#manifest.assetsPrefix);
3391
- }
3392
- }
3393
- },
3394
- routeCache: new RouteCache(this.#logging),
3395
- site: this.#manifest.site,
3396
- ssr: true,
3397
- streaming
3398
- });
3399
- }
3400
- set setManifestData(newManifestData) {
3401
- this.#manifestData = newManifestData;
3402
- }
3403
- removeBase(pathname) {
3404
- if (pathname.startsWith(this.#manifest.base)) {
3405
- return pathname.slice(this.#baseWithoutTrailingSlash.length + 1);
3406
- }
3407
- return pathname;
3408
- }
3409
- // Disable no-unused-vars to avoid breaking signature change
3410
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
3411
- match(request, _opts = {}) {
3412
- const url = new URL(request.url);
3413
- if (this.#manifest.assets.has(url.pathname))
3414
- return void 0;
3415
- const pathname = prependForwardSlash(this.removeBase(url.pathname));
3416
- const routeData = matchRoute(pathname, this.#manifestData);
3417
- if (!routeData || routeData.prerender)
3418
- return void 0;
3419
- return routeData;
3420
- }
3421
- async render(request, routeData, locals) {
3422
- if (request.url !== collapseDuplicateSlashes(request.url)) {
3423
- request = new Request(collapseDuplicateSlashes(request.url), request);
3424
- }
3425
- if (!routeData) {
3426
- routeData = this.match(request);
3427
- }
3428
- if (!routeData) {
3429
- return this.#renderError(request, { status: 404 });
3430
- }
3431
- Reflect.set(request, clientLocalsSymbol, locals ?? {});
3432
- const defaultStatus = this.#getDefaultStatusCode(routeData.route);
3433
- const mod = await this.#getModuleForRoute(routeData);
3434
- const pageModule = await mod.page();
3435
- const url = new URL(request.url);
3436
- const renderContext = await this.#createRenderContext(
3437
- url,
3438
- request,
3439
- routeData,
3440
- mod,
3441
- defaultStatus
3442
- );
3443
- let response;
3444
- try {
3445
- response = await tryRenderRoute(
3446
- routeData.type,
3447
- renderContext,
3448
- this.#env,
3449
- pageModule,
3450
- mod.onRequest
3451
- );
3452
- } catch (err) {
3453
- error(this.#logging, "ssr", err.stack || err.message || String(err));
3454
- return this.#renderError(request, { status: 500 });
3455
- }
3456
- if (isResponse(response, routeData.type)) {
3457
- if (STATUS_CODES.has(response.status)) {
3458
- return this.#renderError(request, {
3459
- response,
3460
- status: response.status
3461
- });
3462
- }
3463
- Reflect.set(response, responseSentSymbol, true);
3464
- return response;
3465
- } else {
3466
- if (response.type === "response") {
3467
- if (response.response.headers.get("X-Astro-Response") === "Not-Found") {
3468
- return this.#renderError(request, {
3469
- response: response.response,
3470
- status: 404
3471
- });
3472
- }
3473
- return response.response;
3474
- } else {
3475
- const headers = new Headers();
3476
- const mimeType = mime.getType(url.pathname);
3477
- if (mimeType) {
3478
- headers.set("Content-Type", `${mimeType};charset=utf-8`);
3479
- } else {
3480
- headers.set("Content-Type", "text/plain;charset=utf-8");
3481
- }
3482
- const bytes = response.encoding !== "binary" ? this.#encoder.encode(response.body) : response.body;
3483
- headers.set("Content-Length", bytes.byteLength.toString());
3484
- const newResponse = new Response(bytes, {
3485
- status: 200,
3486
- headers
3487
- });
3488
- attachToResponse(newResponse, response.cookies);
3489
- return newResponse;
3490
- }
3491
- }
3492
- }
3493
- setCookieHeaders(response) {
3494
- return getSetCookiesFromResponse(response);
3495
- }
3496
- /**
3497
- * Creates the render context of the current route
3498
- */
3499
- async #createRenderContext(url, request, routeData, page, status = 200) {
3500
- if (routeData.type === "endpoint") {
3501
- const pathname = "/" + this.removeBase(url.pathname);
3502
- const mod = await page.page();
3503
- const handler = mod;
3504
- return await createRenderContext({
3505
- request,
3506
- pathname,
3507
- route: routeData,
3508
- status,
3509
- env: this.#env,
3510
- mod: handler
3511
- });
3512
- } else {
3513
- const pathname = prependForwardSlash(this.removeBase(url.pathname));
3514
- const info = this.#routeDataToRouteInfo.get(routeData);
3515
- const links = /* @__PURE__ */ new Set();
3516
- const styles = createStylesheetElementSet(info.styles);
3517
- let scripts = /* @__PURE__ */ new Set();
3518
- for (const script of info.scripts) {
3519
- if ("stage" in script) {
3520
- if (script.stage === "head-inline") {
3521
- scripts.add({
3522
- props: {},
3523
- children: script.children
3524
- });
3525
- }
3526
- } else {
3527
- scripts.add(createModuleScriptElement(script));
3528
- }
3529
- }
3530
- const mod = await page.page();
3531
- return await createRenderContext({
3532
- request,
3533
- pathname,
3534
- componentMetadata: this.#manifest.componentMetadata,
3535
- scripts,
3536
- styles,
3537
- links,
3538
- route: routeData,
3539
- status,
3540
- mod,
3541
- env: this.#env
3542
- });
3543
- }
3544
- }
3545
- /**
3546
- * If it is a known error code, try sending the according page (e.g. 404.astro / 500.astro).
3547
- * This also handles pre-rendered /404 or /500 routes
3548
- */
3549
- async #renderError(request, { status, response: originalResponse }) {
3550
- const errorRouteData = matchRoute("/" + status, this.#manifestData);
3551
- const url = new URL(request.url);
3552
- if (errorRouteData) {
3553
- if (errorRouteData.prerender) {
3554
- const maybeDotHtml = errorRouteData.route.endsWith(`/${status}`) ? ".html" : "";
3555
- const statusURL = new URL(
3556
- `${this.#baseWithoutTrailingSlash}/${status}${maybeDotHtml}`,
3557
- url
3558
- );
3559
- const response2 = await fetch(statusURL.toString());
3560
- const override = { status };
3561
- return this.#mergeResponses(response2, originalResponse, override);
3562
- }
3563
- const mod = await this.#getModuleForRoute(errorRouteData);
3564
- try {
3565
- const newRenderContext = await this.#createRenderContext(
3566
- url,
3567
- request,
3568
- errorRouteData,
3569
- mod,
3570
- status
3571
- );
3572
- const page = await mod.page();
3573
- const response2 = await tryRenderRoute(
3574
- "page",
3575
- // this is hardcoded to ensure proper behavior for missing endpoints
3576
- newRenderContext,
3577
- this.#env,
3578
- page
3579
- );
3580
- return this.#mergeResponses(response2, originalResponse);
3581
- } catch {
3582
- }
3583
- }
3584
- const response = this.#mergeResponses(new Response(null, { status }), originalResponse);
3585
- Reflect.set(response, responseSentSymbol, true);
3586
- return response;
3587
- }
3588
- #mergeResponses(newResponse, oldResponse, override) {
3589
- if (!oldResponse) {
3590
- if (override !== void 0) {
3591
- return new Response(newResponse.body, {
3592
- status: override.status,
3593
- statusText: newResponse.statusText,
3594
- headers: newResponse.headers
3595
- });
3596
- }
3597
- return newResponse;
3598
- }
3599
- const { statusText, headers } = oldResponse;
3600
- const status = (override == null ? void 0 : override.status) ? override.status : oldResponse.status === 200 ? newResponse.status : oldResponse.status;
3601
- return new Response(newResponse.body, {
3602
- status,
3603
- statusText: status === 200 ? newResponse.statusText : statusText,
3604
- headers: new Headers(Array.from(headers))
3605
- });
3606
- }
3607
- #getDefaultStatusCode(route) {
3608
- route = removeTrailingForwardSlash(route);
3609
- if (route.endsWith("/404"))
3610
- return 404;
3611
- if (route.endsWith("/500"))
3612
- return 500;
3613
- return 200;
3614
- }
3615
- async #getModuleForRoute(route) {
3616
- if (route.type === "redirect") {
3617
- return RedirectSinglePageBuiltModule;
3618
- } else {
3619
- if (this.#manifest.pageMap) {
3620
- const importComponentInstance = this.#manifest.pageMap.get(route.component);
3621
- if (!importComponentInstance) {
3622
- throw new Error(
3623
- `Unexpectedly unable to find a component instance for route ${route.route}`
3624
- );
3625
- }
3626
- const pageModule = await importComponentInstance();
3627
- return pageModule;
3628
- } else if (this.#manifest.pageModule) {
3629
- const importComponentInstance = this.#manifest.pageModule;
3630
- return importComponentInstance;
3631
- } else {
3632
- throw new Error(
3633
- "Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error, please file an issue."
3634
- );
3635
- }
3636
- }
3637
- }
3638
- }
3639
-
3640
- const clientAddressSymbol = Symbol.for("astro.clientAddress");
3641
- function createRequestFromNodeRequest(req, options) {
3642
- var _a;
3643
- const protocol = req.socket instanceof TLSSocket || req.headers["x-forwarded-proto"] === "https" ? "https" : "http";
3644
- const hostname = req.headers.host || req.headers[":authority"];
3645
- const url = `${protocol}://${hostname}${req.url}`;
3646
- const headers = makeRequestHeaders(req);
3647
- const method = req.method || "GET";
3648
- let bodyProps = {};
3649
- const bodyAllowed = method !== "HEAD" && method !== "GET" && !(options == null ? void 0 : options.emptyBody);
3650
- if (bodyAllowed) {
3651
- bodyProps = makeRequestBody(req);
3652
- }
3653
- const request = new Request(url, {
3654
- method,
3655
- headers,
3656
- ...bodyProps
3657
- });
3658
- if ((_a = req.socket) == null ? void 0 : _a.remoteAddress) {
3659
- Reflect.set(request, clientAddressSymbol, req.socket.remoteAddress);
3660
- }
3661
- return request;
3662
- }
3663
- function makeRequestHeaders(req) {
3664
- const headers = new Headers();
3665
- for (const [name, value] of Object.entries(req.headers)) {
3666
- if (value === void 0) {
3667
- continue;
3668
- }
3669
- if (Array.isArray(value)) {
3670
- for (const item of value) {
3671
- headers.append(name, item);
3672
- }
3673
- } else {
3674
- headers.append(name, value);
3675
- }
3676
- }
3677
- return headers;
3678
- }
3679
- function makeRequestBody(req) {
3680
- if (req.body !== void 0) {
3681
- if (typeof req.body === "string" && req.body.length > 0) {
3682
- return { body: Buffer.from(req.body) };
3683
- }
3684
- if (typeof req.body === "object" && req.body !== null && Object.keys(req.body).length > 0) {
3685
- return { body: Buffer.from(JSON.stringify(req.body)) };
3686
- }
3687
- if (typeof req.body === "object" && req.body !== null && typeof req.body[Symbol.asyncIterator] !== "undefined") {
3688
- return asyncIterableToBodyProps(req.body);
3689
- }
3690
- }
3691
- return asyncIterableToBodyProps(req);
3692
- }
3693
- function asyncIterableToBodyProps(iterable) {
3694
- return {
3695
- // Node uses undici for the Request implementation. Undici accepts
3696
- // a non-standard async iterable for the body.
3697
- // @ts-expect-error
3698
- body: iterable,
3699
- // The duplex property is required when using a ReadableStream or async
3700
- // iterable for the body. The type definitions do not include the duplex
3701
- // property because they are not up-to-date.
3702
- // @ts-expect-error
3703
- duplex: "half"
3704
- };
3705
- }
3706
- class NodeApp extends App {
3707
- match(req, opts = {}) {
3708
- if (!(req instanceof Request)) {
3709
- req = createRequestFromNodeRequest(req, {
3710
- emptyBody: true
3711
- });
3712
- }
3713
- return super.match(req, opts);
3714
- }
3715
- render(req, routeData, locals) {
3716
- if (!(req instanceof Request)) {
3717
- req = createRequestFromNodeRequest(req);
3718
- }
3719
- return super.render(req, routeData, locals);
3720
- }
3721
- }
3722
-
3723
- export { Fragment as F, NodeApp as N, createComponent as a, renderComponent as b, createAstro as c, addAttribute as d, renderSlotToString as e, renderAllHeadContent as f, renderSlot as g, deserializeManifest as h, server_default as i, maybeRenderHead as m, renderTemplate as r, spreadAttributes as s, unescapeHTML as u };
2013
+ export { AstroError as A, MiddlewareNotAResponse as B, ClientAddressNotAvailable as C, ASTRO_VERSION as D, ExpectedImage as E, Fragment as F, GetStaticPathsRequired as G, renderEndpoint as H, InvalidImageService as I, MissingSharp as J, LocalImageUsedWrongly as L, MissingImageDimension as M, NoMatchingStaticPathFound as N, PageNumberParamNotFound as P, ReservedSlotName as R, StaticClientAddressNotAvailable as S, UnsupportedImageFormat as U, ExpectedImageOptions as a, createComponent as b, createAstro as c, ImageMissingAlt as d, addAttribute as e, renderComponent as f, renderSlotToString as g, renderAllHeadContent as h, renderSlot as i, InvalidGetStaticPathsReturn as j, InvalidGetStaticPathsEntry as k, GetStaticPathsExpectedParams as l, maybeRenderHead as m, GetStaticPathsInvalidRouteParam as n, GetStaticPathsRemovedRSSHelper as o, PrerenderDynamicEndpointPathCollide as p, LocalsNotAnObject as q, renderTemplate as r, spreadAttributes as s, renderJSX as t, unescapeHTML as u, chunkToString as v, ResponseSentError as w, renderPage as x, AstroUserError as y, MiddlewareNoDataOrNextCalled as z };