_@astrojs-ssr-adapter_DpluC3qk.mjs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. globalThis.process ??= {}; globalThis.process.env ??= {};
  2. import { f as fileExtension, j as joinPaths, s as slash, p as prependForwardSlash, r as removeTrailingForwardSlash, a as appendForwardSlash, b as isInternalPath, c as collapseDuplicateTrailingSlashes, h as hasFileExtension } from './path_CH3auf61.mjs';
  3. import { m as matchPattern } from './remote_BC1y8RCW.mjs';
  4. import { r as requestIs404Or500, i as isRequestServerIsland, n as notFound, a as redirectToFallback, b as redirectToDefaultLocale, c as requestHasLocale, d as normalizeTheLocale, e as defineMiddleware, S as SERVER_ISLAND_COMPONENT, f as SERVER_ISLAND_ROUTE, g as createEndpoint, R as RouteCache, s as sequence, h as findRouteToRewrite, m as matchRoute, j as RenderContext, P as PERSIST_SYMBOL, k as getSetCookiesFromResponse } from './index_BfW_FHpJ.mjs';
  5. import { R as ROUTE_TYPE_HEADER, q as REROUTE_DIRECTIVE_HEADER, D as DEFAULT_404_COMPONENT, A as AstroError, v as ActionNotFoundError, w as bold, x as red, y as yellow, z as dim, B as blue, C as clientAddressSymbol, G as LocalsNotAnObject, H as REROUTABLE_STATUS_CODES, J as responseSentSymbol } from './astro/server_WO3f6Mge.mjs';
  6. import { D as DEFAULT_404_ROUTE, d as default404Instance, e as ensure404Route } from './astro-designed-error-pages_CuMapJD2.mjs';
  7. import { N as NOOP_MIDDLEWARE_FN } from './noop-middleware_C9xlyid3.mjs';
  8. import 'cloudflare:workers';
  9. function createI18nMiddleware(i18n, base, trailingSlash, format) {
  10. if (!i18n) return (_, next) => next();
  11. const payload = {
  12. ...i18n,
  13. trailingSlash,
  14. base,
  15. format};
  16. const _redirectToDefaultLocale = redirectToDefaultLocale(payload);
  17. const _noFoundForNonLocaleRoute = notFound(payload);
  18. const _requestHasLocale = requestHasLocale(payload.locales);
  19. const _redirectToFallback = redirectToFallback(payload);
  20. const prefixAlways = (context, response) => {
  21. const url = context.url;
  22. if (url.pathname === base + "/" || url.pathname === base) {
  23. return _redirectToDefaultLocale(context);
  24. } else if (!_requestHasLocale(context)) {
  25. return _noFoundForNonLocaleRoute(context, response);
  26. }
  27. return void 0;
  28. };
  29. const prefixOtherLocales = (context, response) => {
  30. let pathnameContainsDefaultLocale = false;
  31. const url = context.url;
  32. for (const segment of url.pathname.split("/")) {
  33. if (normalizeTheLocale(segment) === normalizeTheLocale(i18n.defaultLocale)) {
  34. pathnameContainsDefaultLocale = true;
  35. break;
  36. }
  37. }
  38. if (pathnameContainsDefaultLocale) {
  39. const newLocation = url.pathname.replace(`/${i18n.defaultLocale}`, "");
  40. response.headers.set("Location", newLocation);
  41. return _noFoundForNonLocaleRoute(context);
  42. }
  43. return void 0;
  44. };
  45. return async (context, next) => {
  46. const response = await next();
  47. const type = response.headers.get(ROUTE_TYPE_HEADER);
  48. const isReroute = response.headers.get(REROUTE_DIRECTIVE_HEADER);
  49. if (isReroute === "no" && typeof i18n.fallback === "undefined") {
  50. return response;
  51. }
  52. if (type !== "page" && type !== "fallback") {
  53. return response;
  54. }
  55. if (requestIs404Or500(context.request, base)) {
  56. return response;
  57. }
  58. if (isRequestServerIsland(context.request, base)) {
  59. return response;
  60. }
  61. const { currentLocale } = context;
  62. switch (i18n.strategy) {
  63. // NOTE: theoretically, we should never hit this code path
  64. case "manual": {
  65. return response;
  66. }
  67. case "domains-prefix-other-locales": {
  68. if (localeHasntDomain(i18n, currentLocale)) {
  69. const result = prefixOtherLocales(context, response);
  70. if (result) {
  71. return result;
  72. }
  73. }
  74. break;
  75. }
  76. case "pathname-prefix-other-locales": {
  77. const result = prefixOtherLocales(context, response);
  78. if (result) {
  79. return result;
  80. }
  81. break;
  82. }
  83. case "domains-prefix-always-no-redirect": {
  84. if (localeHasntDomain(i18n, currentLocale)) {
  85. const result = _noFoundForNonLocaleRoute(context, response);
  86. if (result) {
  87. return result;
  88. }
  89. }
  90. break;
  91. }
  92. case "pathname-prefix-always-no-redirect": {
  93. const result = _noFoundForNonLocaleRoute(context, response);
  94. if (result) {
  95. return result;
  96. }
  97. break;
  98. }
  99. case "pathname-prefix-always": {
  100. const result = prefixAlways(context, response);
  101. if (result) {
  102. return result;
  103. }
  104. break;
  105. }
  106. case "domains-prefix-always": {
  107. if (localeHasntDomain(i18n, currentLocale)) {
  108. const result = prefixAlways(context, response);
  109. if (result) {
  110. return result;
  111. }
  112. }
  113. break;
  114. }
  115. }
  116. return _redirectToFallback(context, response);
  117. };
  118. }
  119. function localeHasntDomain(i18n, currentLocale) {
  120. for (const domainLocale of Object.values(i18n.domainLookupTable)) {
  121. if (domainLocale === currentLocale) {
  122. return false;
  123. }
  124. }
  125. return true;
  126. }
  127. const NOOP_ACTIONS_MOD = {
  128. server: {}
  129. };
  130. const FORM_CONTENT_TYPES = [
  131. "application/x-www-form-urlencoded",
  132. "multipart/form-data",
  133. "text/plain"
  134. ];
  135. const SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
  136. function createOriginCheckMiddleware() {
  137. return defineMiddleware((context, next) => {
  138. const { request, url, isPrerendered } = context;
  139. if (isPrerendered) {
  140. return next();
  141. }
  142. if (SAFE_METHODS.includes(request.method)) {
  143. return next();
  144. }
  145. const isSameOrigin = request.headers.get("origin") === url.origin;
  146. const hasContentType = request.headers.has("content-type");
  147. if (hasContentType) {
  148. const formLikeHeader = hasFormLikeHeader(request.headers.get("content-type"));
  149. if (formLikeHeader && !isSameOrigin) {
  150. return new Response(`Cross-site ${request.method} form submissions are forbidden`, {
  151. status: 403
  152. });
  153. }
  154. } else {
  155. if (!isSameOrigin) {
  156. return new Response(`Cross-site ${request.method} form submissions are forbidden`, {
  157. status: 403
  158. });
  159. }
  160. }
  161. return next();
  162. });
  163. }
  164. function hasFormLikeHeader(contentType) {
  165. if (contentType) {
  166. for (const FORM_CONTENT_TYPE of FORM_CONTENT_TYPES) {
  167. if (contentType.toLowerCase().includes(FORM_CONTENT_TYPE)) {
  168. return true;
  169. }
  170. }
  171. }
  172. return false;
  173. }
  174. function createDefaultRoutes(manifest) {
  175. const root = new URL(manifest.hrefRoot);
  176. return [
  177. {
  178. instance: default404Instance,
  179. matchesComponent: (filePath) => filePath.href === new URL(DEFAULT_404_COMPONENT, root).href,
  180. route: DEFAULT_404_ROUTE.route,
  181. component: DEFAULT_404_COMPONENT
  182. },
  183. {
  184. instance: createEndpoint(manifest),
  185. matchesComponent: (filePath) => filePath.href === new URL(SERVER_ISLAND_COMPONENT, root).href,
  186. route: SERVER_ISLAND_ROUTE,
  187. component: SERVER_ISLAND_COMPONENT
  188. }
  189. ];
  190. }
  191. class Pipeline {
  192. constructor(logger, manifest, runtimeMode, renderers, resolve, serverLike, streaming, adapterName = manifest.adapterName, clientDirectives = manifest.clientDirectives, inlinedScripts = manifest.inlinedScripts, compressHTML = manifest.compressHTML, i18n = manifest.i18n, middleware = manifest.middleware, routeCache = new RouteCache(logger, runtimeMode), site = manifest.site ? new URL(manifest.site) : void 0, defaultRoutes = createDefaultRoutes(manifest), actions = manifest.actions) {
  193. this.logger = logger;
  194. this.manifest = manifest;
  195. this.runtimeMode = runtimeMode;
  196. this.renderers = renderers;
  197. this.resolve = resolve;
  198. this.serverLike = serverLike;
  199. this.streaming = streaming;
  200. this.adapterName = adapterName;
  201. this.clientDirectives = clientDirectives;
  202. this.inlinedScripts = inlinedScripts;
  203. this.compressHTML = compressHTML;
  204. this.i18n = i18n;
  205. this.middleware = middleware;
  206. this.routeCache = routeCache;
  207. this.site = site;
  208. this.defaultRoutes = defaultRoutes;
  209. this.actions = actions;
  210. this.internalMiddleware = [];
  211. if (i18n?.strategy !== "manual") {
  212. this.internalMiddleware.push(
  213. createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat)
  214. );
  215. }
  216. }
  217. internalMiddleware;
  218. resolvedMiddleware = void 0;
  219. resolvedActions = void 0;
  220. /**
  221. * Resolves the middleware from the manifest, and returns the `onRequest` function. If `onRequest` isn't there,
  222. * it returns a no-op function
  223. */
  224. async getMiddleware() {
  225. if (this.resolvedMiddleware) {
  226. return this.resolvedMiddleware;
  227. } else if (this.middleware) {
  228. const middlewareInstance = await this.middleware();
  229. const onRequest = middlewareInstance.onRequest ?? NOOP_MIDDLEWARE_FN;
  230. const internalMiddlewares = [onRequest];
  231. if (this.manifest.checkOrigin) {
  232. internalMiddlewares.unshift(createOriginCheckMiddleware());
  233. }
  234. this.resolvedMiddleware = sequence(...internalMiddlewares);
  235. return this.resolvedMiddleware;
  236. } else {
  237. this.resolvedMiddleware = NOOP_MIDDLEWARE_FN;
  238. return this.resolvedMiddleware;
  239. }
  240. }
  241. setActions(actions) {
  242. this.resolvedActions = actions;
  243. }
  244. async getActions() {
  245. if (this.resolvedActions) {
  246. return this.resolvedActions;
  247. } else if (this.actions) {
  248. return await this.actions();
  249. }
  250. return NOOP_ACTIONS_MOD;
  251. }
  252. async getAction(path) {
  253. const pathKeys = path.split(".").map((key) => decodeURIComponent(key));
  254. let { server } = await this.getActions();
  255. if (!server || !(typeof server === "object")) {
  256. throw new TypeError(
  257. `Expected \`server\` export in actions file to be an object. Received ${typeof server}.`
  258. );
  259. }
  260. for (const key of pathKeys) {
  261. if (!(key in server)) {
  262. throw new AstroError({
  263. ...ActionNotFoundError,
  264. message: ActionNotFoundError.message(pathKeys.join("."))
  265. });
  266. }
  267. server = server[key];
  268. }
  269. if (typeof server !== "function") {
  270. throw new TypeError(
  271. `Expected handler for action ${pathKeys.join(".")} to be a function. Received ${typeof server}.`
  272. );
  273. }
  274. return server;
  275. }
  276. }
  277. const RedirectComponentInstance = {
  278. default() {
  279. return new Response(null, {
  280. status: 301
  281. });
  282. }
  283. };
  284. const RedirectSinglePageBuiltModule = {
  285. page: () => Promise.resolve(RedirectComponentInstance),
  286. onRequest: (_, next) => next(),
  287. renderers: []
  288. };
  289. const dateTimeFormat = new Intl.DateTimeFormat([], {
  290. hour: "2-digit",
  291. minute: "2-digit",
  292. second: "2-digit",
  293. hour12: false
  294. });
  295. const levels = {
  296. debug: 20,
  297. info: 30,
  298. warn: 40,
  299. error: 50,
  300. silent: 90
  301. };
  302. function log(opts, level, label, message, newLine = true) {
  303. const logLevel = opts.level;
  304. const dest = opts.dest;
  305. const event = {
  306. label,
  307. level,
  308. message,
  309. newLine
  310. };
  311. if (!isLogLevelEnabled(logLevel, level)) {
  312. return;
  313. }
  314. dest.write(event);
  315. }
  316. function isLogLevelEnabled(configuredLogLevel, level) {
  317. return levels[configuredLogLevel] <= levels[level];
  318. }
  319. function info(opts, label, message, newLine = true) {
  320. return log(opts, "info", label, message, newLine);
  321. }
  322. function warn(opts, label, message, newLine = true) {
  323. return log(opts, "warn", label, message, newLine);
  324. }
  325. function error(opts, label, message, newLine = true) {
  326. return log(opts, "error", label, message, newLine);
  327. }
  328. function debug(...args) {
  329. if ("_astroGlobalDebug" in globalThis) {
  330. globalThis._astroGlobalDebug(...args);
  331. }
  332. }
  333. function getEventPrefix({ level, label }) {
  334. const timestamp = `${dateTimeFormat.format(/* @__PURE__ */ new Date())}`;
  335. const prefix = [];
  336. if (level === "error" || level === "warn") {
  337. prefix.push(bold(timestamp));
  338. prefix.push(`[${level.toUpperCase()}]`);
  339. } else {
  340. prefix.push(timestamp);
  341. }
  342. if (label) {
  343. prefix.push(`[${label}]`);
  344. }
  345. if (level === "error") {
  346. return red(prefix.join(" "));
  347. }
  348. if (level === "warn") {
  349. return yellow(prefix.join(" "));
  350. }
  351. if (prefix.length === 1) {
  352. return dim(prefix[0]);
  353. }
  354. return dim(prefix[0]) + " " + blue(prefix.splice(1).join(" "));
  355. }
  356. class Logger {
  357. options;
  358. constructor(options) {
  359. this.options = options;
  360. }
  361. info(label, message, newLine = true) {
  362. info(this.options, label, message, newLine);
  363. }
  364. warn(label, message, newLine = true) {
  365. warn(this.options, label, message, newLine);
  366. }
  367. error(label, message, newLine = true) {
  368. error(this.options, label, message, newLine);
  369. }
  370. debug(label, ...messages) {
  371. debug(label, ...messages);
  372. }
  373. level() {
  374. return this.options.level;
  375. }
  376. forkIntegrationLogger(label) {
  377. return new AstroIntegrationLogger(this.options, label);
  378. }
  379. }
  380. class AstroIntegrationLogger {
  381. options;
  382. label;
  383. constructor(logging, label) {
  384. this.options = logging;
  385. this.label = label;
  386. }
  387. /**
  388. * Creates a new logger instance with a new label, but the same log options.
  389. */
  390. fork(label) {
  391. return new AstroIntegrationLogger(this.options, label);
  392. }
  393. info(message) {
  394. info(this.options, this.label, message);
  395. }
  396. warn(message) {
  397. warn(this.options, this.label, message);
  398. }
  399. error(message) {
  400. error(this.options, this.label, message);
  401. }
  402. debug(message) {
  403. debug(this.label, message);
  404. }
  405. }
  406. const consoleLogDestination = {
  407. write(event) {
  408. let dest = console.error;
  409. if (levels[event.level] < levels["error"]) {
  410. dest = console.info;
  411. }
  412. if (event.label === "SKIP_FORMAT") {
  413. dest(event.message);
  414. } else {
  415. dest(getEventPrefix(event) + " " + event.message);
  416. }
  417. return true;
  418. }
  419. };
  420. function getAssetsPrefix(fileExtension, assetsPrefix) {
  421. if (!assetsPrefix) return "";
  422. if (typeof assetsPrefix === "string") return assetsPrefix;
  423. const dotLessFileExtension = fileExtension.slice(1);
  424. if (assetsPrefix[dotLessFileExtension]) {
  425. return assetsPrefix[dotLessFileExtension];
  426. }
  427. return assetsPrefix.fallback;
  428. }
  429. function createAssetLink(href, base, assetsPrefix) {
  430. if (assetsPrefix) {
  431. const pf = getAssetsPrefix(fileExtension(href), assetsPrefix);
  432. return joinPaths(pf, slash(href));
  433. } else if (base) {
  434. return prependForwardSlash(joinPaths(base, slash(href)));
  435. } else {
  436. return href;
  437. }
  438. }
  439. function createStylesheetElement(stylesheet, base, assetsPrefix) {
  440. if (stylesheet.type === "inline") {
  441. return {
  442. props: {},
  443. children: stylesheet.content
  444. };
  445. } else {
  446. return {
  447. props: {
  448. rel: "stylesheet",
  449. href: createAssetLink(stylesheet.src, base, assetsPrefix)
  450. },
  451. children: ""
  452. };
  453. }
  454. }
  455. function createStylesheetElementSet(stylesheets, base, assetsPrefix) {
  456. return new Set(stylesheets.map((s) => createStylesheetElement(s, base, assetsPrefix)));
  457. }
  458. function createModuleScriptElement(script, base, assetsPrefix) {
  459. if (script.type === "external") {
  460. return createModuleScriptElementWithSrc(script.value, base, assetsPrefix);
  461. } else {
  462. return {
  463. props: {
  464. type: "module"
  465. },
  466. children: script.value
  467. };
  468. }
  469. }
  470. function createModuleScriptElementWithSrc(src, base, assetsPrefix) {
  471. return {
  472. props: {
  473. type: "module",
  474. src: createAssetLink(src, base, assetsPrefix)
  475. },
  476. children: ""
  477. };
  478. }
  479. function redirectTemplate({
  480. status,
  481. absoluteLocation,
  482. relativeLocation,
  483. from
  484. }) {
  485. const delay = status === 302 ? 2 : 0;
  486. return `<!doctype html>
  487. <title>Redirecting to: ${relativeLocation}</title>
  488. <meta http-equiv="refresh" content="${delay};url=${relativeLocation}">
  489. <meta name="robots" content="noindex">
  490. <link rel="canonical" href="${absoluteLocation}">
  491. <body>
  492. <a href="${relativeLocation}">Redirecting ${from ? `from <code>${from}</code> ` : ""}to <code>${relativeLocation}</code></a>
  493. </body>`;
  494. }
  495. class AppPipeline extends Pipeline {
  496. static create({
  497. logger,
  498. manifest,
  499. runtimeMode,
  500. renderers,
  501. resolve,
  502. serverLike,
  503. streaming,
  504. defaultRoutes
  505. }) {
  506. const pipeline = new AppPipeline(
  507. logger,
  508. manifest,
  509. runtimeMode,
  510. renderers,
  511. resolve,
  512. serverLike,
  513. streaming,
  514. void 0,
  515. void 0,
  516. void 0,
  517. void 0,
  518. void 0,
  519. void 0,
  520. void 0,
  521. void 0,
  522. defaultRoutes
  523. );
  524. return pipeline;
  525. }
  526. headElements(routeData) {
  527. const routeInfo = this.manifest.routes.find((route) => route.routeData === routeData);
  528. const links = /* @__PURE__ */ new Set();
  529. const scripts = /* @__PURE__ */ new Set();
  530. const styles = createStylesheetElementSet(routeInfo?.styles ?? []);
  531. for (const script of routeInfo?.scripts ?? []) {
  532. if ("stage" in script) {
  533. if (script.stage === "head-inline") {
  534. scripts.add({
  535. props: {},
  536. children: script.children
  537. });
  538. }
  539. } else {
  540. scripts.add(createModuleScriptElement(script));
  541. }
  542. }
  543. return { links, styles, scripts };
  544. }
  545. componentMetadata() {
  546. }
  547. async getComponentByRoute(routeData) {
  548. const module = await this.getModuleForRoute(routeData);
  549. return module.page();
  550. }
  551. async tryRewrite(payload, request) {
  552. const { newUrl, pathname, routeData } = findRouteToRewrite({
  553. payload,
  554. request,
  555. routes: this.manifest?.routes.map((r) => r.routeData),
  556. trailingSlash: this.manifest.trailingSlash,
  557. buildFormat: this.manifest.buildFormat,
  558. base: this.manifest.base,
  559. outDir: this.serverLike ? this.manifest.buildClientDir : this.manifest.outDir
  560. });
  561. const componentInstance = await this.getComponentByRoute(routeData);
  562. return { newUrl, pathname, componentInstance, routeData };
  563. }
  564. async getModuleForRoute(route) {
  565. for (const defaultRoute of this.defaultRoutes) {
  566. if (route.component === defaultRoute.component) {
  567. return {
  568. page: () => Promise.resolve(defaultRoute.instance),
  569. renderers: []
  570. };
  571. }
  572. }
  573. if (route.type === "redirect") {
  574. return RedirectSinglePageBuiltModule;
  575. } else {
  576. if (this.manifest.pageMap) {
  577. const importComponentInstance = this.manifest.pageMap.get(route.component);
  578. if (!importComponentInstance) {
  579. throw new Error(
  580. `Unexpectedly unable to find a component instance for route ${route.route}`
  581. );
  582. }
  583. return await importComponentInstance();
  584. } else if (this.manifest.pageModule) {
  585. return this.manifest.pageModule;
  586. }
  587. throw new Error(
  588. "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."
  589. );
  590. }
  591. }
  592. }
  593. class App {
  594. #manifest;
  595. #manifestData;
  596. #logger = new Logger({
  597. dest: consoleLogDestination,
  598. level: "info"
  599. });
  600. #baseWithoutTrailingSlash;
  601. #pipeline;
  602. #adapterLogger;
  603. constructor(manifest, streaming = true) {
  604. this.#manifest = manifest;
  605. this.#manifestData = {
  606. routes: manifest.routes.map((route) => route.routeData)
  607. };
  608. ensure404Route(this.#manifestData);
  609. this.#baseWithoutTrailingSlash = removeTrailingForwardSlash(this.#manifest.base);
  610. this.#pipeline = this.#createPipeline(streaming);
  611. this.#adapterLogger = new AstroIntegrationLogger(
  612. this.#logger.options,
  613. this.#manifest.adapterName
  614. );
  615. }
  616. getAdapterLogger() {
  617. return this.#adapterLogger;
  618. }
  619. getAllowedDomains() {
  620. return this.#manifest.allowedDomains;
  621. }
  622. get manifest() {
  623. return this.#manifest;
  624. }
  625. set manifest(value) {
  626. this.#manifest = value;
  627. }
  628. matchesAllowedDomains(forwardedHost, protocol) {
  629. return App.validateForwardedHost(forwardedHost, this.#manifest.allowedDomains, protocol);
  630. }
  631. static validateForwardedHost(forwardedHost, allowedDomains, protocol) {
  632. if (!allowedDomains || allowedDomains.length === 0) {
  633. return false;
  634. }
  635. try {
  636. const testUrl = new URL(`${protocol || "https"}://${forwardedHost}`);
  637. return allowedDomains.some((pattern) => {
  638. return matchPattern(testUrl, pattern);
  639. });
  640. } catch {
  641. return false;
  642. }
  643. }
  644. /**
  645. * Creates a pipeline by reading the stored manifest
  646. *
  647. * @param streaming
  648. * @private
  649. */
  650. #createPipeline(streaming = false) {
  651. return AppPipeline.create({
  652. logger: this.#logger,
  653. manifest: this.#manifest,
  654. runtimeMode: "production",
  655. renderers: this.#manifest.renderers,
  656. defaultRoutes: createDefaultRoutes(this.#manifest),
  657. resolve: async (specifier) => {
  658. if (!(specifier in this.#manifest.entryModules)) {
  659. throw new Error(`Unable to resolve [${specifier}]`);
  660. }
  661. const bundlePath = this.#manifest.entryModules[specifier];
  662. if (bundlePath.startsWith("data:") || bundlePath.length === 0) {
  663. return bundlePath;
  664. } else {
  665. return createAssetLink(bundlePath, this.#manifest.base, this.#manifest.assetsPrefix);
  666. }
  667. },
  668. serverLike: true,
  669. streaming
  670. });
  671. }
  672. set setManifestData(newManifestData) {
  673. this.#manifestData = newManifestData;
  674. }
  675. removeBase(pathname) {
  676. if (pathname.startsWith(this.#manifest.base)) {
  677. return pathname.slice(this.#baseWithoutTrailingSlash.length + 1);
  678. }
  679. return pathname;
  680. }
  681. /**
  682. * It removes the base from the request URL, prepends it with a forward slash and attempts to decoded it.
  683. *
  684. * If the decoding fails, it logs the error and return the pathname as is.
  685. * @param request
  686. * @private
  687. */
  688. #getPathnameFromRequest(request) {
  689. const url = new URL(request.url);
  690. const pathname = prependForwardSlash(this.removeBase(url.pathname));
  691. try {
  692. return decodeURI(pathname);
  693. } catch (e) {
  694. this.getAdapterLogger().error(e.toString());
  695. return pathname;
  696. }
  697. }
  698. /**
  699. * Given a `Request`, it returns the `RouteData` that matches its `pathname`. By default, prerendered
  700. * routes aren't returned, even if they are matched.
  701. *
  702. * When `allowPrerenderedRoutes` is `true`, the function returns matched prerendered routes too.
  703. * @param request
  704. * @param allowPrerenderedRoutes
  705. */
  706. match(request, allowPrerenderedRoutes = false) {
  707. const url = new URL(request.url);
  708. if (this.#manifest.assets.has(url.pathname)) return void 0;
  709. let pathname = this.#computePathnameFromDomain(request);
  710. if (!pathname) {
  711. pathname = prependForwardSlash(this.removeBase(url.pathname));
  712. }
  713. let routeData = matchRoute(decodeURI(pathname), this.#manifestData);
  714. if (!routeData) return void 0;
  715. if (allowPrerenderedRoutes) {
  716. return routeData;
  717. } else if (routeData.prerender) {
  718. return void 0;
  719. }
  720. return routeData;
  721. }
  722. #computePathnameFromDomain(request) {
  723. let pathname = void 0;
  724. const url = new URL(request.url);
  725. if (this.#manifest.i18n && (this.#manifest.i18n.strategy === "domains-prefix-always" || this.#manifest.i18n.strategy === "domains-prefix-other-locales" || this.#manifest.i18n.strategy === "domains-prefix-always-no-redirect")) {
  726. let forwardedHost = request.headers.get("X-Forwarded-Host");
  727. let protocol = request.headers.get("X-Forwarded-Proto");
  728. if (protocol) {
  729. protocol = protocol + ":";
  730. } else {
  731. protocol = url.protocol;
  732. }
  733. if (forwardedHost && !this.matchesAllowedDomains(forwardedHost, protocol?.replace(":", ""))) {
  734. forwardedHost = null;
  735. }
  736. let host = forwardedHost;
  737. if (!host) {
  738. host = request.headers.get("Host");
  739. }
  740. if (host && protocol) {
  741. host = host.split(":")[0];
  742. try {
  743. let locale;
  744. const hostAsUrl = new URL(`${protocol}//${host}`);
  745. for (const [domainKey, localeValue] of Object.entries(
  746. this.#manifest.i18n.domainLookupTable
  747. )) {
  748. const domainKeyAsUrl = new URL(domainKey);
  749. if (hostAsUrl.host === domainKeyAsUrl.host && hostAsUrl.protocol === domainKeyAsUrl.protocol) {
  750. locale = localeValue;
  751. break;
  752. }
  753. }
  754. if (locale) {
  755. pathname = prependForwardSlash(
  756. joinPaths(normalizeTheLocale(locale), this.removeBase(url.pathname))
  757. );
  758. if (url.pathname.endsWith("/")) {
  759. pathname = appendForwardSlash(pathname);
  760. }
  761. }
  762. } catch (e) {
  763. this.#logger.error(
  764. "router",
  765. `Astro tried to parse ${protocol}//${host} as an URL, but it threw a parsing error. Check the X-Forwarded-Host and X-Forwarded-Proto headers.`
  766. );
  767. this.#logger.error("router", `Error: ${e}`);
  768. }
  769. }
  770. }
  771. return pathname;
  772. }
  773. #redirectTrailingSlash(pathname) {
  774. const { trailingSlash } = this.#manifest;
  775. if (pathname === "/" || isInternalPath(pathname)) {
  776. return pathname;
  777. }
  778. const path = collapseDuplicateTrailingSlashes(pathname, trailingSlash !== "never");
  779. if (path !== pathname) {
  780. return path;
  781. }
  782. if (trailingSlash === "ignore") {
  783. return pathname;
  784. }
  785. if (trailingSlash === "always" && !hasFileExtension(pathname)) {
  786. return appendForwardSlash(pathname);
  787. }
  788. if (trailingSlash === "never") {
  789. return removeTrailingForwardSlash(pathname);
  790. }
  791. return pathname;
  792. }
  793. async render(request, renderOptions) {
  794. let routeData;
  795. let locals;
  796. let clientAddress;
  797. let addCookieHeader;
  798. const url = new URL(request.url);
  799. const redirect = this.#redirectTrailingSlash(url.pathname);
  800. const prerenderedErrorPageFetch = renderOptions?.prerenderedErrorPageFetch ?? fetch;
  801. if (redirect !== url.pathname) {
  802. const status = request.method === "GET" ? 301 : 308;
  803. return new Response(
  804. redirectTemplate({
  805. status,
  806. relativeLocation: url.pathname,
  807. absoluteLocation: redirect,
  808. from: request.url
  809. }),
  810. {
  811. status,
  812. headers: {
  813. location: redirect + url.search
  814. }
  815. }
  816. );
  817. }
  818. addCookieHeader = renderOptions?.addCookieHeader;
  819. clientAddress = renderOptions?.clientAddress ?? Reflect.get(request, clientAddressSymbol);
  820. routeData = renderOptions?.routeData;
  821. locals = renderOptions?.locals;
  822. if (routeData) {
  823. this.#logger.debug(
  824. "router",
  825. "The adapter " + this.#manifest.adapterName + " provided a custom RouteData for ",
  826. request.url
  827. );
  828. this.#logger.debug("router", "RouteData:\n" + routeData);
  829. }
  830. if (locals) {
  831. if (typeof locals !== "object") {
  832. const error = new AstroError(LocalsNotAnObject);
  833. this.#logger.error(null, error.stack);
  834. return this.#renderError(request, {
  835. status: 500,
  836. error,
  837. clientAddress,
  838. prerenderedErrorPageFetch
  839. });
  840. }
  841. }
  842. if (!routeData) {
  843. routeData = this.match(request);
  844. this.#logger.debug("router", "Astro matched the following route for " + request.url);
  845. this.#logger.debug("router", "RouteData:\n" + routeData);
  846. }
  847. if (!routeData) {
  848. routeData = this.#manifestData.routes.find(
  849. (route) => route.component === "404.astro" || route.component === DEFAULT_404_COMPONENT
  850. );
  851. }
  852. if (!routeData) {
  853. this.#logger.debug("router", "Astro hasn't found routes that match " + request.url);
  854. this.#logger.debug("router", "Here's the available routes:\n", this.#manifestData);
  855. return this.#renderError(request, {
  856. locals,
  857. status: 404,
  858. clientAddress,
  859. prerenderedErrorPageFetch
  860. });
  861. }
  862. const pathname = this.#getPathnameFromRequest(request);
  863. const defaultStatus = this.#getDefaultStatusCode(routeData, pathname);
  864. let response;
  865. let session;
  866. try {
  867. const mod = await this.#pipeline.getModuleForRoute(routeData);
  868. const renderContext = await RenderContext.create({
  869. pipeline: this.#pipeline,
  870. locals,
  871. pathname,
  872. request,
  873. routeData,
  874. status: defaultStatus,
  875. clientAddress
  876. });
  877. session = renderContext.session;
  878. response = await renderContext.render(await mod.page());
  879. } catch (err) {
  880. this.#logger.error(null, err.stack || err.message || String(err));
  881. return this.#renderError(request, {
  882. locals,
  883. status: 500,
  884. error: err,
  885. clientAddress,
  886. prerenderedErrorPageFetch
  887. });
  888. } finally {
  889. await session?.[PERSIST_SYMBOL]();
  890. }
  891. if (REROUTABLE_STATUS_CODES.includes(response.status) && response.headers.get(REROUTE_DIRECTIVE_HEADER) !== "no") {
  892. return this.#renderError(request, {
  893. locals,
  894. response,
  895. status: response.status,
  896. // We don't have an error to report here. Passing null means we pass nothing intentionally
  897. // while undefined means there's no error
  898. error: response.status === 500 ? null : void 0,
  899. clientAddress,
  900. prerenderedErrorPageFetch
  901. });
  902. }
  903. if (response.headers.has(REROUTE_DIRECTIVE_HEADER)) {
  904. response.headers.delete(REROUTE_DIRECTIVE_HEADER);
  905. }
  906. if (addCookieHeader) {
  907. for (const setCookieHeaderValue of App.getSetCookieFromResponse(response)) {
  908. response.headers.append("set-cookie", setCookieHeaderValue);
  909. }
  910. }
  911. Reflect.set(response, responseSentSymbol, true);
  912. return response;
  913. }
  914. setCookieHeaders(response) {
  915. return getSetCookiesFromResponse(response);
  916. }
  917. /**
  918. * Reads all the cookies written by `Astro.cookie.set()` onto the passed response.
  919. * For example,
  920. * ```ts
  921. * for (const cookie_ of App.getSetCookieFromResponse(response)) {
  922. * const cookie: string = cookie_
  923. * }
  924. * ```
  925. * @param response The response to read cookies from.
  926. * @returns An iterator that yields key-value pairs as equal-sign-separated strings.
  927. */
  928. static getSetCookieFromResponse = getSetCookiesFromResponse;
  929. /**
  930. * If it is a known error code, try sending the according page (e.g. 404.astro / 500.astro).
  931. * This also handles pre-rendered /404 or /500 routes
  932. */
  933. async #renderError(request, {
  934. locals,
  935. status,
  936. response: originalResponse,
  937. skipMiddleware = false,
  938. error,
  939. clientAddress,
  940. prerenderedErrorPageFetch
  941. }) {
  942. const errorRoutePath = `/${status}${this.#manifest.trailingSlash === "always" ? "/" : ""}`;
  943. const errorRouteData = matchRoute(errorRoutePath, this.#manifestData);
  944. const url = new URL(request.url);
  945. if (errorRouteData) {
  946. if (errorRouteData.prerender) {
  947. const maybeDotHtml = errorRouteData.route.endsWith(`/${status}`) ? ".html" : "";
  948. const statusURL = new URL(
  949. `${this.#baseWithoutTrailingSlash}/${status}${maybeDotHtml}`,
  950. url
  951. );
  952. if (statusURL.toString() !== request.url) {
  953. const response2 = await prerenderedErrorPageFetch(statusURL.toString());
  954. const override = { status, removeContentEncodingHeaders: true };
  955. return this.#mergeResponses(response2, originalResponse, override);
  956. }
  957. }
  958. const mod = await this.#pipeline.getModuleForRoute(errorRouteData);
  959. let session;
  960. try {
  961. const renderContext = await RenderContext.create({
  962. locals,
  963. pipeline: this.#pipeline,
  964. middleware: skipMiddleware ? NOOP_MIDDLEWARE_FN : void 0,
  965. pathname: this.#getPathnameFromRequest(request),
  966. request,
  967. routeData: errorRouteData,
  968. status,
  969. props: { error },
  970. clientAddress
  971. });
  972. session = renderContext.session;
  973. const response2 = await renderContext.render(await mod.page());
  974. return this.#mergeResponses(response2, originalResponse);
  975. } catch {
  976. if (skipMiddleware === false) {
  977. return this.#renderError(request, {
  978. locals,
  979. status,
  980. response: originalResponse,
  981. skipMiddleware: true,
  982. clientAddress,
  983. prerenderedErrorPageFetch
  984. });
  985. }
  986. } finally {
  987. await session?.[PERSIST_SYMBOL]();
  988. }
  989. }
  990. const response = this.#mergeResponses(new Response(null, { status }), originalResponse);
  991. Reflect.set(response, responseSentSymbol, true);
  992. return response;
  993. }
  994. #mergeResponses(newResponse, originalResponse, override) {
  995. let newResponseHeaders = newResponse.headers;
  996. if (override?.removeContentEncodingHeaders) {
  997. newResponseHeaders = new Headers(newResponseHeaders);
  998. newResponseHeaders.delete("Content-Encoding");
  999. newResponseHeaders.delete("Content-Length");
  1000. }
  1001. if (!originalResponse) {
  1002. if (override !== void 0) {
  1003. return new Response(newResponse.body, {
  1004. status: override.status,
  1005. statusText: newResponse.statusText,
  1006. headers: newResponseHeaders
  1007. });
  1008. }
  1009. return newResponse;
  1010. }
  1011. const status = override?.status ? override.status : originalResponse.status === 200 ? newResponse.status : originalResponse.status;
  1012. try {
  1013. originalResponse.headers.delete("Content-type");
  1014. } catch {
  1015. }
  1016. const mergedHeaders = new Map([
  1017. ...Array.from(newResponseHeaders),
  1018. ...Array.from(originalResponse.headers)
  1019. ]);
  1020. const newHeaders = new Headers();
  1021. for (const [name, value] of mergedHeaders) {
  1022. newHeaders.set(name, value);
  1023. }
  1024. return new Response(newResponse.body, {
  1025. status,
  1026. statusText: status === 200 ? newResponse.statusText : originalResponse.statusText,
  1027. // If you're looking at here for possible bugs, it means that it's not a bug.
  1028. // With the middleware, users can meddle with headers, and we should pass to the 404/500.
  1029. // If users see something weird, it's because they are setting some headers they should not.
  1030. //
  1031. // Although, we don't want it to replace the content-type, because the error page must return `text/html`
  1032. headers: newHeaders
  1033. });
  1034. }
  1035. #getDefaultStatusCode(routeData, pathname) {
  1036. if (!routeData.pattern.test(pathname)) {
  1037. for (const fallbackRoute of routeData.fallbackRoutes) {
  1038. if (fallbackRoute.pattern.test(pathname)) {
  1039. return 302;
  1040. }
  1041. }
  1042. }
  1043. const route = removeTrailingForwardSlash(routeData.route);
  1044. if (route.endsWith("/404")) return 404;
  1045. if (route.endsWith("/500")) return 500;
  1046. return 200;
  1047. }
  1048. }
  1049. async function handle(manifest, app, request, env, context) {
  1050. const { pathname } = new URL(request.url);
  1051. const bindingName = "SESSION";
  1052. globalThis.__env__ ??= {};
  1053. globalThis.__env__[bindingName] = env[bindingName];
  1054. if (manifest.assets.has(pathname)) {
  1055. return env.ASSETS.fetch(request.url.replace(/\.html$/, ""));
  1056. }
  1057. const routeData = app.match(request);
  1058. if (!routeData) {
  1059. const asset = await env.ASSETS.fetch(
  1060. request.url.replace(/index.html$/, "").replace(/\.html$/, "")
  1061. );
  1062. if (asset.status !== 404) {
  1063. return asset;
  1064. }
  1065. }
  1066. Reflect.set(request, Symbol.for("astro.clientAddress"), request.headers.get("cf-connecting-ip"));
  1067. const locals = {
  1068. runtime: {
  1069. env,
  1070. cf: request.cf,
  1071. caches,
  1072. ctx: {
  1073. waitUntil: (promise) => context.waitUntil(promise),
  1074. // Currently not available: https://developers.cloudflare.com/pages/platform/known-issues/#pages-functions
  1075. passThroughOnException: () => {
  1076. throw new Error(
  1077. "`passThroughOnException` is currently not available in Cloudflare Pages. See https://developers.cloudflare.com/pages/platform/known-issues/#pages-functions."
  1078. );
  1079. },
  1080. props: {}
  1081. }
  1082. }
  1083. };
  1084. const response = await app.render(
  1085. request,
  1086. {
  1087. routeData,
  1088. locals,
  1089. prerenderedErrorPageFetch: async (url) => {
  1090. return env.ASSETS.fetch(url.replace(/\.html$/, ""));
  1091. }
  1092. }
  1093. );
  1094. if (app.setCookieHeaders) {
  1095. for (const setCookieHeader of app.setCookieHeaders(response)) {
  1096. response.headers.append("Set-Cookie", setCookieHeader);
  1097. }
  1098. }
  1099. return response;
  1100. }
  1101. function createExports(manifest) {
  1102. const app = new App(manifest);
  1103. const fetch = async (request, env, context) => {
  1104. return await handle(manifest, app, request, env, context);
  1105. };
  1106. return { default: { fetch } };
  1107. }
  1108. const serverEntrypointModule = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  1109. __proto__: null,
  1110. createExports
  1111. }, Symbol.toStringTag, { value: 'Module' }));
  1112. export { createExports as c, serverEntrypointModule as s };