adapter.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.adapter = adapter;
  6. exports.blockUnallowedResponse = blockUnallowedResponse;
  7. exports.enhanceGlobals = enhanceGlobals;
  8. var _error = require("./error");
  9. var _utils = require("./utils");
  10. var _fetchEvent = require("./spec-extension/fetch-event");
  11. var _request = require("./spec-extension/request");
  12. var _response = require("./spec-extension/response");
  13. var _relativizeUrl = require("../../shared/lib/router/utils/relativize-url");
  14. var _nextUrl = require("./next-url");
  15. var _internalUtils = require("../internal-utils");
  16. class NextRequestHint extends _request.NextRequest {
  17. constructor(params){
  18. super(params.input, params.init);
  19. this.sourcePage = params.page;
  20. }
  21. get request() {
  22. throw new _error.PageSignatureError({
  23. page: this.sourcePage
  24. });
  25. }
  26. respondWith() {
  27. throw new _error.PageSignatureError({
  28. page: this.sourcePage
  29. });
  30. }
  31. waitUntil() {
  32. throw new _error.PageSignatureError({
  33. page: this.sourcePage
  34. });
  35. }
  36. }
  37. async function adapter(params) {
  38. // TODO-APP: use explicit marker for this
  39. const isEdgeRendering = typeof self.__BUILD_MANIFEST !== "undefined";
  40. const requestUrl = new _nextUrl.NextURL(params.request.url, {
  41. headers: params.request.headers,
  42. nextConfig: params.request.nextConfig
  43. });
  44. // Ensure users only see page requests, never data requests.
  45. const buildId = requestUrl.buildId;
  46. requestUrl.buildId = "";
  47. const isDataReq = params.request.headers["x-nextjs-data"];
  48. if (isDataReq && requestUrl.pathname === "/index") {
  49. requestUrl.pathname = "/";
  50. }
  51. // Preserve flight data.
  52. const flightSearchParameters = requestUrl.flightSearchParameters;
  53. // Parameters should only be stripped for middleware
  54. if (!isEdgeRendering) {
  55. requestUrl.flightSearchParameters = undefined;
  56. }
  57. // Strip internal query parameters off the request.
  58. (0, _internalUtils).stripInternalSearchParams(requestUrl.searchParams, true);
  59. const request = new NextRequestHint({
  60. page: params.page,
  61. input: String(requestUrl),
  62. init: {
  63. body: params.request.body,
  64. geo: params.request.geo,
  65. headers: (0, _utils).fromNodeHeaders(params.request.headers),
  66. ip: params.request.ip,
  67. method: params.request.method,
  68. nextConfig: params.request.nextConfig
  69. }
  70. });
  71. /**
  72. * This allows to identify the request as a data request. The user doesn't
  73. * need to know about this property neither use it. We add it for testing
  74. * purposes.
  75. */ if (isDataReq) {
  76. Object.defineProperty(request, "__isData", {
  77. enumerable: false,
  78. value: true
  79. });
  80. }
  81. const event = new _fetchEvent.NextFetchEvent({
  82. request,
  83. page: params.page
  84. });
  85. let response = await params.handler(request, event);
  86. /**
  87. * For rewrites we must always include the locale in the final pathname
  88. * so we re-create the NextURL forcing it to include it when the it is
  89. * an internal rewrite. Also we make sure the outgoing rewrite URL is
  90. * a data URL if the request was a data request.
  91. */ const rewrite = response == null ? void 0 : response.headers.get("x-middleware-rewrite");
  92. if (response && rewrite) {
  93. const rewriteUrl = new _nextUrl.NextURL(rewrite, {
  94. forceLocale: true,
  95. headers: params.request.headers,
  96. nextConfig: params.request.nextConfig
  97. });
  98. if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
  99. if (rewriteUrl.host === request.nextUrl.host) {
  100. rewriteUrl.buildId = buildId || rewriteUrl.buildId;
  101. rewriteUrl.flightSearchParameters = flightSearchParameters || rewriteUrl.flightSearchParameters;
  102. response.headers.set("x-middleware-rewrite", String(rewriteUrl));
  103. }
  104. }
  105. /**
  106. * When the request is a data request we must show if there was a rewrite
  107. * with an internal header so the client knows which component to load
  108. * from the data request.
  109. */ if (isDataReq) {
  110. response.headers.set("x-nextjs-rewrite", (0, _relativizeUrl).relativizeURL(String(rewriteUrl), String(requestUrl)));
  111. }
  112. }
  113. /**
  114. * For redirects we will not include the locale in case when it is the
  115. * default and we must also make sure the outgoing URL is a data one if
  116. * the incoming request was a data request.
  117. */ const redirect = response == null ? void 0 : response.headers.get("Location");
  118. if (response && redirect) {
  119. const redirectURL = new _nextUrl.NextURL(redirect, {
  120. forceLocale: false,
  121. headers: params.request.headers,
  122. nextConfig: params.request.nextConfig
  123. });
  124. /**
  125. * Responses created from redirects have immutable headers so we have
  126. * to clone the response to be able to modify it.
  127. */ response = new Response(response.body, response);
  128. if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
  129. if (redirectURL.host === request.nextUrl.host) {
  130. redirectURL.buildId = buildId || redirectURL.buildId;
  131. redirectURL.flightSearchParameters = flightSearchParameters || redirectURL.flightSearchParameters;
  132. response.headers.set("Location", String(redirectURL));
  133. }
  134. }
  135. /**
  136. * When the request is a data request we can't use the location header as
  137. * it may end up with CORS error. Instead we map to an internal header so
  138. * the client knows the destination.
  139. */ if (isDataReq) {
  140. response.headers.delete("Location");
  141. response.headers.set("x-nextjs-redirect", (0, _relativizeUrl).relativizeURL(String(redirectURL), String(requestUrl)));
  142. }
  143. }
  144. return {
  145. response: response || _response.NextResponse.next(),
  146. waitUntil: Promise.all(event[_fetchEvent.waitUntilSymbol])
  147. };
  148. }
  149. function blockUnallowedResponse(promise) {
  150. if (process.env.__NEXT_ALLOW_MIDDLEWARE_RESPONSE_BODY) {
  151. return promise;
  152. }
  153. return promise.then((result)=>{
  154. var ref;
  155. if ((ref = result.response) == null ? void 0 : ref.body) {
  156. console.error(new Error(`A middleware can not alter response's body. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware`));
  157. return {
  158. ...result,
  159. response: new Response("Internal Server Error", {
  160. status: 500,
  161. statusText: "Internal Server Error"
  162. })
  163. };
  164. }
  165. return result;
  166. });
  167. }
  168. function getUnsupportedModuleErrorMessage(module) {
  169. // warning: if you change these messages, you must adjust how react-dev-overlay's middleware detects modules not found
  170. return `The edge runtime does not support Node.js '${module}' module.
  171. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`;
  172. }
  173. function __import_unsupported(moduleName) {
  174. const proxy = new Proxy(function() {}, {
  175. get (_obj, prop) {
  176. if (prop === "then") {
  177. return {};
  178. }
  179. throw new Error(getUnsupportedModuleErrorMessage(moduleName));
  180. },
  181. construct () {
  182. throw new Error(getUnsupportedModuleErrorMessage(moduleName));
  183. },
  184. apply (_target, _this, args) {
  185. if (typeof args[0] === "function") {
  186. return args[0](proxy);
  187. }
  188. throw new Error(getUnsupportedModuleErrorMessage(moduleName));
  189. }
  190. });
  191. return new Proxy({}, {
  192. get: ()=>proxy
  193. });
  194. }
  195. function enhanceGlobals() {
  196. // The condition is true when the "process" module is provided
  197. if (process !== global.process) {
  198. // prefer local process but global.process has correct "env"
  199. process.env = global.process.env;
  200. global.process = process;
  201. }
  202. // to allow building code that import but does not use node.js modules,
  203. // webpack will expect this function to exist in global scope
  204. Object.defineProperty(globalThis, "__import_unsupported", {
  205. value: __import_unsupported,
  206. enumerable: false,
  207. configurable: false
  208. });
  209. }
  210. //# sourceMappingURL=adapter.js.map