create project

This commit is contained in:
ismailsosic
2022-12-27 12:05:56 +01:00
parent 2a33a2d3de
commit cd2143287c
16035 changed files with 2489703 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
import { IncomingMessage, ServerResponse } from 'http';
import { ServerlessHandlerCtx } from './utils';
import { NodeNextResponse, NodeNextRequest } from '../../../../server/base-http/node';
export declare function getApiHandler(ctx: ServerlessHandlerCtx): (rawReq: NodeNextRequest | IncomingMessage, rawRes: NodeNextResponse | ServerResponse) => Promise<void>;

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getApiHandler = getApiHandler;
var _url = require("url");
var _http = require("http");
var _node = require("../../../../server/api-utils/node");
var _utils = require("./utils");
var _utils1 = require("../../../../shared/lib/utils");
var _node1 = require("../../../../server/base-http/node");
function getApiHandler(ctx) {
const { pageModule , encodedPreviewProps , pageIsDynamic } = ctx;
const { handleRewrites , handleBasePath , dynamicRouteMatcher , normalizeDynamicRouteParams , } = (0, _utils).getUtils(ctx);
return async (rawReq, rawRes)=>{
const req = rawReq instanceof _http.IncomingMessage ? new _node1.NodeNextRequest(rawReq) : rawReq;
const res = rawRes instanceof _http.ServerResponse ? new _node1.NodeNextResponse(rawRes) : rawRes;
try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = req.headers[_utils.vercelHeader];
const parsedUrl = (0, _url).parse(req.url, true);
handleRewrites(req, parsedUrl);
if (parsedUrl.query.nextInternalLocale) {
delete parsedUrl.query.nextInternalLocale;
}
handleBasePath(req, parsedUrl);
let params = {};
if (pageIsDynamic) {
const result = normalizeDynamicRouteParams(trustQuery ? parsedUrl.query : dynamicRouteMatcher(parsedUrl.pathname));
params = result.params;
}
await (0, _node).apiResolver(req.originalRequest, res.originalResponse, Object.assign({}, parsedUrl.query, params), await pageModule, encodedPreviewProps, true);
} catch (err) {
console.error(err);
if (err instanceof _utils1.DecodeError) {
res.statusCode = 400;
res.body("Bad Request").send();
} else {
// Throw the error to crash the serverless function
throw err;
}
}
};
}
//# sourceMappingURL=api-handler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-serverless-loader/api-handler.ts"],"names":["getApiHandler","ctx","pageModule","encodedPreviewProps","pageIsDynamic","handleRewrites","handleBasePath","dynamicRouteMatcher","normalizeDynamicRouteParams","getUtils","rawReq","rawRes","req","IncomingMessage","NodeNextRequest","res","ServerResponse","NodeNextResponse","trustQuery","headers","vercelHeader","parsedUrl","parseUrl","url","query","nextInternalLocale","params","result","pathname","apiResolver","originalRequest","originalResponse","Object","assign","err","console","error","DecodeError","statusCode","body","send"],"mappings":"AAAA;;;;QAUgBA,aAAa,GAAbA,aAAa;AAVK,IAAA,IAAK,WAAL,KAAK,CAAA;AACS,IAAA,KAAM,WAAN,MAAM,CAAA;AAC1B,IAAA,KAAmC,WAAnC,mCAAmC,CAAA;AACF,IAAA,MAAS,WAAT,SAAS,CAAA;AAC1C,IAAA,OAA8B,WAA9B,8BAA8B,CAAA;AAInD,IAAA,MAAmC,WAAnC,mCAAmC,CAAA;AAEnC,SAASA,aAAa,CAACC,GAAyB,EAAE;IACvD,MAAM,EAAEC,UAAU,CAAA,EAAEC,mBAAmB,CAAA,EAAEC,aAAa,CAAA,EAAE,GAAGH,GAAG;IAC9D,MAAM,EACJI,cAAc,CAAA,EACdC,cAAc,CAAA,EACdC,mBAAmB,CAAA,EACnBC,2BAA2B,CAAA,IAC5B,GAAGC,CAAAA,GAAAA,MAAQ,AAAK,CAAA,SAAL,CAACR,GAAG,CAAC;IAEjB,OAAO,OACLS,MAAyC,EACzCC,MAAyC,GACtC;QACH,MAAMC,GAAG,GACPF,MAAM,YAAYG,KAAe,gBAAA,GAAG,IAAIC,MAAe,gBAAA,CAACJ,MAAM,CAAC,GAAGA,MAAM;QAC1E,MAAMK,GAAG,GACPJ,MAAM,YAAYK,KAAc,eAAA,GAAG,IAAIC,MAAgB,iBAAA,CAACN,MAAM,CAAC,GAAGA,M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1,22 @@
import { webpack } from 'next/dist/compiled/webpack/webpack';
export declare type ServerlessLoaderQuery = {
page: string;
distDir: string;
absolutePagePath: string;
absoluteAppPath: string;
absoluteDocumentPath: string;
absoluteErrorPath: string;
absolute404Path: string;
buildId: string;
assetPrefix: string;
generateEtags: string;
poweredByHeader: string;
canonicalBase: string;
basePath: string;
runtimeConfig: string;
previewProps: string;
loadedEnvFiles: string;
i18n: string;
};
declare const nextServerlessLoader: webpack.LoaderDefinitionFunction;
export default nextServerlessLoader;

View File

@@ -0,0 +1,145 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _devalue = _interopRequireDefault(require("next/dist/compiled/devalue"));
var _path = require("path");
var _querystring = require("querystring");
var _isApiRoute = require("../../../../lib/is-api-route");
var _utils = require("../../../../shared/lib/router/utils");
var _escapeRegexp = require("../../../../shared/lib/escape-regexp");
var _constants = require("../../../../shared/lib/constants");
var _stringifyRequest = require("../../stringify-request");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const nextServerlessLoader = function() {
const { distDir , absolutePagePath , page , buildId , canonicalBase , assetPrefix , absoluteAppPath , absoluteDocumentPath , absoluteErrorPath , absolute404Path , generateEtags , poweredByHeader , basePath , runtimeConfig , previewProps , loadedEnvFiles , i18n , } = typeof this.query === "string" ? (0, _querystring).parse(this.query.slice(1)) : this.query;
const buildManifest = (0, _path).join(distDir, _constants.BUILD_MANIFEST).replace(/\\/g, "/");
const reactLoadableManifest = (0, _path).join(distDir, _constants.REACT_LOADABLE_MANIFEST).replace(/\\/g, "/");
const routesManifest = (0, _path).join(distDir, _constants.ROUTES_MANIFEST).replace(/\\/g, "/");
const escapedBuildId = (0, _escapeRegexp).escapeStringRegexp(buildId);
const pageIsDynamicRoute = (0, _utils).isDynamicRoute(page);
const encodedPreviewProps = (0, _devalue).default(JSON.parse(previewProps));
const envLoading = `
const { processEnv } = require('@next/env')
processEnv(${Buffer.from(loadedEnvFiles, "base64").toString()})
`;
const runtimeConfigImports = runtimeConfig ? `
const { setConfig } = require('next/config')
` : "";
const runtimeConfigSetter = runtimeConfig ? `
const runtimeConfig = ${runtimeConfig}
setConfig(runtimeConfig)
` : "const runtimeConfig = {}";
if ((0, _isApiRoute).isAPIRoute(page)) {
return `
${envLoading}
${runtimeConfigImports}
${/*
this needs to be called first so its available for any other imports
*/ runtimeConfigSetter}
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler'
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const apiHandler = getApiHandler({
pageModule: require(${(0, _stringifyRequest).stringifyRequest(this, absolutePagePath)}),
rewrites: rewrites,
i18n: ${i18n || "undefined"},
page: "${page}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export default apiHandler
`;
} else {
return `
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import buildManifest from '${buildManifest}'
import reactLoadableManifest from '${reactLoadableManifest}'
${envLoading}
${runtimeConfigImports}
${// this needs to be called first so its available for any other imports
runtimeConfigSetter}
import { getPageHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/page-handler'
const documentModule = require(${(0, _stringifyRequest).stringifyRequest(this, absoluteDocumentPath)})
const appMod = require(${(0, _stringifyRequest).stringifyRequest(this, absoluteAppPath)})
let App = appMod.default || appMod.then && appMod.then(mod => mod.default);
const compMod = require(${(0, _stringifyRequest).stringifyRequest(this, absolutePagePath)})
const Component = compMod.default || compMod.then && compMod.then(mod => mod.default)
export default Component
export const getStaticProps = compMod['getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['getStaticProp' + 's'])
export const getStaticPaths = compMod['getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['getStaticPath' + 's'])
export const getServerSideProps = compMod['getServerSideProp' + 's'] || compMod.then && compMod.then(mod => mod['getServerSideProp' + 's'])
// kept for detecting legacy exports
export const unstable_getStaticParams = compMod['unstable_getStaticParam' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticParam' + 's'])
export const unstable_getStaticProps = compMod['unstable_getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticProp' + 's'])
export const unstable_getStaticPaths = compMod['unstable_getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticPath' + 's'])
export const unstable_getServerProps = compMod['unstable_getServerProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getServerProp' + 's'])
export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
export const _app = App
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const { renderReqToHTML, render } = getPageHandler({
pageModule: compMod,
pageComponent: Component,
pageConfig: config,
appModule: App,
documentModule: documentModule,
errorModule: require(${(0, _stringifyRequest).stringifyRequest(this, absoluteErrorPath)}),
notFoundModule: ${absolute404Path ? `require(${(0, _stringifyRequest).stringifyRequest(this, absolute404Path)})` : undefined},
pageGetStaticProps: getStaticProps,
pageGetStaticPaths: getStaticPaths,
pageGetServerSideProps: getServerSideProps,
assetPrefix: "${assetPrefix}",
canonicalBase: "${canonicalBase}",
generateEtags: ${generateEtags || "false"},
poweredByHeader: ${poweredByHeader || "false"},
runtimeConfig,
buildManifest,
reactLoadableManifest,
rewrites: rewrites,
i18n: ${i18n || "undefined"},
page: "${page}",
buildId: "${buildId}",
escapedBuildId: "${escapedBuildId}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export { renderReqToHTML, render }
`;
}
};
var _default = nextServerlessLoader;
exports.default = _default;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-serverless-loader/index.ts"],"names":["nextServerlessLoader","distDir","absolutePagePath","page","buildId","canonicalBase","assetPrefix","absoluteAppPath","absoluteDocumentPath","absoluteErrorPath","absolute404Path","generateEtags","poweredByHeader","basePath","runtimeConfig","previewProps","loadedEnvFiles","i18n","query","parse","slice","buildManifest","join","BUILD_MANIFEST","replace","reactLoadableManifest","REACT_LOADABLE_MANIFEST","routesManifest","ROUTES_MANIFEST","escapedBuildId","escapeStringRegexp","pageIsDynamicRoute","isDynamicRoute","encodedPreviewProps","devalue","JSON","envLoading","Buffer","from","toString","runtimeConfigImports","runtimeConfigSetter","isAPIRoute","stringifyRequest","undefined"],"mappings":"AAAA;;;;;AAAoB,IAAA,QAA4B,kCAA5B,4BAA4B,EAAA;AAC3B,IAAA,KAAM,WAAN,MAAM,CAAA;AACL,IAAA,YAAa,WAAb,aAAa,CAAA;AAER,IAAA,WAA8B,WAA9B,8BAA8B,CAAA;AAC1B,IAAA,MAAqC,WAArC,qCAAqC,CAAA;AACjC,IAAA,aAAsC,WAAtC,sCAAsC,CAAA;AAMlE,IAAA,UAAkC,WAAlC,kCAAkC,CAAA;AACR,IAAA,iBAAyB,WAAzB,yBAAyB,CAAA;;;;;;AAsB1D,MAAMA,oBAAoB,GAAqC,WAAY;IACzE,MAAM,EACJC,OAAO,CAAA,EACPC,gBAAgB,CAAA,EAChBC,IAAI,CAAA,EACJC,OAAO,CAAA,EACPC,aAAa,CAAA,EACbC,WAAW,CAAA,EACXC,eAAe,CAAA,EACfC,oBAAoB,CAAA,EACpBC,iBAAiB,CAAA,EACjBC,eAAe,CAAA,EACfC,aAAa,CAAA,EACbC,eAAe,CAAA,EACfC,QAAQ,CAAA,EACRC,aAAa,CAAA,EACbC,YAAY,CAAA,EACZC,cAAc,CAAA,EACdC,IAAI,CAAA,IACL,GACC,OAAO,IAAI,CAACC,KAAK,KAAK,QAAQ,GAAGC,CAAAA,GAAAA,YAAK,AAAqB,CAAA,MAArB,CAAC,IAAI,CAACD,KAAK,CAACE,KAAK,CAAC,CAAC,CA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IAAI,OAAO,CAAC;yBACzB,EAAEC,eAAe,IAAI,OAAO,CAAC;;;;;;;cAOxC,EAAEK,IAAI,IAAI,WAAW,CAAC;eACrB,EAAEd,IAAI,CAAC;kBACJ,EAAEC,OAAO,CAAC;yBACH,EAAEyB,cAAc,CAAC;mBACvB,EAAEhB,QAAQ,CAAC;uBACP,EAAEkB,kBAAkB,CAAC;6BACf,EAAEE,mBAAmB,CAAC;;;IAG/C,CAAC,CAAA;KACF;CACF;eAEcjC,oBAAoB"}

View File

@@ -0,0 +1,10 @@
import { IncomingMessage, ServerResponse } from 'http';
import { ServerlessHandlerCtx } from './utils';
import RenderResult from '../../../../server/render-result';
export declare function getPageHandler(ctx: ServerlessHandlerCtx): {
renderReqToHTML: (req: IncomingMessage, res: ServerResponse, renderMode?: 'export' | 'passthrough' | true, _renderOpts?: any, _params?: any) => Promise<string | {
html: RenderResult | null;
renderOpts: any;
} | null>;
render: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
};

View File

@@ -0,0 +1,337 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getPageHandler = getPageHandler;
var _url = require("url");
var _utils = require("../../../../shared/lib/utils");
var _sendPayload = require("../../../../server/send-payload");
var _utils1 = require("./utils");
var _render = require("../../../../server/render");
var _node = require("../../../../server/api-utils/node");
var _denormalizePagePath = require("../../../../shared/lib/page-path/denormalize-page-path");
var _apiUtils = require("../../../../server/api-utils");
var _redirectStatus = require("../../../../lib/redirect-status");
var _getRouteFromAssetPath = _interopRequireDefault(require("../../../../shared/lib/router/utils/get-route-from-asset-path"));
var _constants = require("../../../../shared/lib/constants");
var _renderResult = _interopRequireDefault(require("../../../../server/render-result"));
var _isError = _interopRequireDefault(require("../../../../lib/is-error"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getPageHandler(ctx) {
const { page , pageComponent , pageConfig , pageGetStaticProps , pageGetStaticPaths , pageGetServerSideProps , appModule , documentModule , errorModule , notFoundModule , encodedPreviewProps , pageIsDynamic , generateEtags , poweredByHeader , runtimeConfig , buildManifest , reactLoadableManifest , i18n , buildId , basePath , assetPrefix , canonicalBase , escapedBuildId , } = ctx;
const { handleLocale , handleRewrites , handleBasePath , defaultRouteRegex , dynamicRouteMatcher , interpolateDynamicPath , getParamsFromRouteMatches , normalizeDynamicRouteParams , normalizeVercelUrl , } = (0, _utils1).getUtils(ctx);
async function renderReqToHTML(req, res, renderMode, _renderOpts, _params) {
let Component;
let App;
let config;
let Document;
let Error;
let notFoundMod;
let getStaticProps;
let getStaticPaths;
let getServerSideProps;
[getStaticProps, getServerSideProps, getStaticPaths, Component, App, config, { default: Document }, { default: Error }, notFoundMod, ] = await Promise.all([
pageGetStaticProps,
pageGetServerSideProps,
pageGetStaticPaths,
pageComponent,
appModule,
pageConfig,
documentModule,
errorModule,
notFoundModule,
]);
const fromExport = renderMode === "export" || renderMode === true;
const nextStartMode = renderMode === "passthrough";
let hasValidParams = true;
(0, _apiUtils).setLazyProp({
req: req
}, "cookies", (0, _apiUtils).getCookieParser(req.headers));
const options = {
App,
Document,
ComponentMod: {
default: Component
},
buildManifest,
getStaticProps,
getServerSideProps,
getStaticPaths,
reactLoadableManifest,
canonicalBase,
buildId,
assetPrefix,
runtimeConfig: (runtimeConfig || {}).publicRuntimeConfig || {},
previewProps: encodedPreviewProps,
env: process.env,
basePath,
supportsDynamicHTML: false,
..._renderOpts
};
let _nextData = false;
let defaultLocale = i18n == null ? void 0 : i18n.defaultLocale;
let detectedLocale = i18n == null ? void 0 : i18n.defaultLocale;
let parsedUrl;
try {
var ref;
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = !getStaticProps && req.headers[_utils1.vercelHeader];
parsedUrl = (0, _url).parse(req.url, true);
let routeNoAssetPath = parsedUrl.pathname;
if (basePath) {
routeNoAssetPath = routeNoAssetPath.replace(new RegExp(`^${basePath}`), "") || "/";
}
const origQuery = Object.assign({}, parsedUrl.query);
handleRewrites(req, parsedUrl);
handleBasePath(req, parsedUrl);
// remove ?amp=1 from request URL if rendering for export
if (fromExport && parsedUrl.query.amp) {
const queryNoAmp = Object.assign({}, origQuery);
delete queryNoAmp.amp;
req.url = (0, _url).format({
...parsedUrl,
search: undefined,
query: queryNoAmp
});
}
if (parsedUrl.pathname.match(/_next\/data/)) {
_nextData = page !== "/_error";
parsedUrl.pathname = (0, _getRouteFromAssetPath).default(parsedUrl.pathname.replace(new RegExp(`/_next/data/${escapedBuildId}/`), "/"), ".json");
routeNoAssetPath = parsedUrl.pathname;
}
const localeResult = handleLocale(req, res, parsedUrl, routeNoAssetPath, fromExport || nextStartMode);
defaultLocale = (localeResult == null ? void 0 : localeResult.defaultLocale) || defaultLocale;
detectedLocale = (localeResult == null ? void 0 : localeResult.detectedLocale) || detectedLocale;
routeNoAssetPath = (localeResult == null ? void 0 : localeResult.routeNoAssetPath) || routeNoAssetPath;
if (parsedUrl.query.nextInternalLocale) {
detectedLocale = parsedUrl.query.nextInternalLocale;
delete parsedUrl.query.nextInternalLocale;
}
const renderOpts = Object.assign({
Component,
pageConfig: config,
nextExport: fromExport,
isDataReq: _nextData,
locales: i18n == null ? void 0 : i18n.locales,
locale: detectedLocale,
defaultLocale,
domainLocales: i18n == null ? void 0 : i18n.domains,
optimizeCss: process.env.__NEXT_OPTIMIZE_CSS,
nextScriptWorkers: process.env.__NEXT_SCRIPT_WORKERS,
crossOrigin: process.env.__NEXT_CROSS_ORIGIN
}, options);
if (page === "/_error" && !res.statusCode) {
res.statusCode = 404;
}
let params = {};
if (!fromExport && pageIsDynamic) {
const result = normalizeDynamicRouteParams(trustQuery ? parsedUrl.query : dynamicRouteMatcher(parsedUrl.pathname));
hasValidParams = result.hasValidParams;
params = result.params;
}
let nowParams = null;
if (pageIsDynamic && !hasValidParams && ((ref = req.headers) == null ? void 0 : ref["x-now-route-matches"])) {
nowParams = getParamsFromRouteMatches(req, renderOpts, detectedLocale);
}
// make sure to set renderOpts to the correct params e.g. _params
// if provided from worker or params if we're parsing them here
renderOpts.params = _params || params;
normalizeVercelUrl(req, !!trustQuery);
// normalize request URL/asPath for fallback/revalidate pages since the
// proxy sets the request URL to the output's path for fallback pages
if (pageIsDynamic && nowParams && defaultRouteRegex) {
const _parsedUrl = (0, _url).parse(req.url);
_parsedUrl.pathname = interpolateDynamicPath(_parsedUrl.pathname, nowParams);
parsedUrl.pathname = _parsedUrl.pathname;
req.url = (0, _url).format(_parsedUrl);
}
// make sure to normalize asPath for revalidate and _next/data requests
// since the asPath should match what is shown on the client
if (!fromExport && (getStaticProps || getServerSideProps)) {
// don't include dynamic route params in query while normalizing
// asPath
if (pageIsDynamic && defaultRouteRegex) {
delete parsedUrl.search;
for (const param of Object.keys(defaultRouteRegex.groups)){
delete origQuery[param];
}
}
parsedUrl.pathname = (0, _denormalizePagePath).denormalizePagePath(parsedUrl.pathname);
renderOpts.resolvedUrl = (0, _url).format({
...parsedUrl,
query: origQuery
});
// For getServerSideProps we need to ensure we use the original URL
// and not the resolved URL to prevent a hydration mismatch on asPath
renderOpts.resolvedAsPath = getServerSideProps ? (0, _url).format({
...parsedUrl,
pathname: routeNoAssetPath,
query: origQuery
}) : renderOpts.resolvedUrl;
}
const isFallback = parsedUrl.query.__nextFallback;
const previewData = (0, _node).tryGetPreviewData(req, res, options.previewProps);
const isPreviewMode = previewData !== false;
if (process.env.__NEXT_OPTIMIZE_FONTS) {
renderOpts.optimizeFonts = process.env.__NEXT_OPTIMIZE_FONTS;
/**
* __webpack_require__.__NEXT_FONT_MANIFEST__ is added by
* font-stylesheet-gathering-plugin
*/ // @ts-ignore
renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__;
}
let result = await (0, _render).renderToHTML(req, res, page, Object.assign({}, getStaticProps ? {
...parsedUrl.query.amp ? {
amp: "1"
} : {}
} : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? {
__nextFallback: "true"
} : {}), renderOpts);
if (!renderMode) {
if (_nextData || getStaticProps || getServerSideProps) {
if (renderOpts.isNotFound) {
res.statusCode = 404;
if (_nextData) {
res.end('{"notFound":true}');
return null;
}
const NotFoundComponent = notFoundMod ? notFoundMod.default : Error;
const errPathname = notFoundMod ? "/404" : "/_error";
const result2 = await (0, _render).renderToHTML(req, res, errPathname, parsedUrl.query, Object.assign({}, options, {
getStaticProps: notFoundMod ? notFoundMod.getStaticProps : undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: NotFoundComponent,
err: undefined,
locale: detectedLocale,
locales: i18n == null ? void 0 : i18n.locales,
defaultLocale: i18n == null ? void 0 : i18n.defaultLocale
}));
(0, _sendPayload).sendRenderResult({
req,
res,
result: result2 ?? _renderResult.default.empty,
type: "html",
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || page === "/404",
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate
}
});
return null;
} else if (renderOpts.isRedirect && !_nextData) {
const redirect = {
destination: renderOpts.pageData.pageProps.__N_REDIRECT,
statusCode: renderOpts.pageData.pageProps.__N_REDIRECT_STATUS,
basePath: renderOpts.pageData.pageProps.__N_REDIRECT_BASE_PATH
};
const statusCode = (0, _redirectStatus).getRedirectStatus(redirect);
if (basePath && redirect.basePath !== false && redirect.destination.startsWith("/")) {
redirect.destination = `${basePath}${redirect.destination}`;
}
if (statusCode === _constants.PERMANENT_REDIRECT_STATUS) {
res.setHeader("Refresh", `0;url=${redirect.destination}`);
}
res.statusCode = statusCode;
res.setHeader("Location", redirect.destination);
res.end(redirect.destination);
return null;
} else {
(0, _sendPayload).sendRenderResult({
req,
res,
result: _nextData ? _renderResult.default.fromStatic(JSON.stringify(renderOpts.pageData)) : result ?? _renderResult.default.empty,
type: _nextData ? "json" : "html",
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || renderOpts.is404Page,
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate
}
});
return null;
}
}
} else if (isPreviewMode) {
res.setHeader("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
}
if (renderMode) return {
html: result,
renderOpts
};
return result ? result.toUnchunkedString() : null;
} catch (err) {
if (!parsedUrl) {
parsedUrl = (0, _url).parse(req.url, true);
}
if ((0, _isError).default(err) && err.code === "ENOENT") {
res.statusCode = 404;
} else if (err instanceof _utils.DecodeError) {
res.statusCode = 400;
} else {
console.error("Unhandled error during request:", err);
// Backwards compat (call getInitialProps in custom error):
try {
await (0, _render).renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: err,
// Short-circuit rendering:
isDataReq: true
}));
} catch (underErrorErr) {
console.error("Failed call /_error subroutine, continuing to crash function:", underErrorErr);
}
// Throw the error to crash the serverless function
if ((0, _utils).isResSent(res)) {
console.error("!!! WARNING !!!");
console.error("Your function crashed, but closed the response before allowing the function to exit.\\n" + "This may cause unexpected behavior for the next request.");
console.error("!!! WARNING !!!");
}
throw err;
}
const result2 = await (0, _render).renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: res.statusCode === 404 ? undefined : err
}));
return result2 ? result2.toUnchunkedString() : null;
}
}
return {
renderReqToHTML,
render: async function render(req, res) {
try {
const html = await renderReqToHTML(req, res);
if (html) {
(0, _sendPayload).sendRenderResult({
req,
res,
result: _renderResult.default.fromStatic(html),
type: "html",
generateEtags,
poweredByHeader
});
}
} catch (err) {
console.error(err);
// Throw the error to crash the serverless function
throw err;
}
}
};
}
//# sourceMappingURL=page-handler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,83 @@
/// <reference types="node" />
/// <reference types="node" />
import type { IncomingMessage, ServerResponse } from 'http';
import type { Rewrite } from '../../../../lib/load-custom-routes';
import type { BuildManifest } from '../../../../server/get-page-files';
import type { RouteMatch } from '../../../../shared/lib/router/utils/route-matcher';
import type { NextConfig } from '../../../../server/config';
import type { GetServerSideProps, GetStaticPaths, GetStaticProps } from '../../../../types';
import type { BaseNextRequest } from '../../../../server/base-http';
import type { __ApiPreviewProps } from '../../../../server/api-utils';
import { UrlWithParsedQuery } from 'url';
import { ParsedUrlQuery } from 'querystring';
import { getNamedRouteRegex } from '../../../../shared/lib/router/utils/route-regex';
export declare const vercelHeader = "x-vercel-id";
export declare type ServerlessHandlerCtx = {
page: string;
pageModule: any;
pageComponent?: any;
pageConfig?: any;
pageGetStaticProps?: GetStaticProps;
pageGetStaticPaths?: GetStaticPaths;
pageGetServerSideProps?: GetServerSideProps;
appModule?: any;
errorModule?: any;
documentModule?: any;
notFoundModule?: any;
runtimeConfig: any;
buildManifest?: BuildManifest;
reactLoadableManifest?: any;
basePath: string;
rewrites: {
fallback?: Rewrite[];
afterFiles?: Rewrite[];
beforeFiles?: Rewrite[];
};
pageIsDynamic: boolean;
generateEtags: boolean;
distDir: string;
buildId: string;
escapedBuildId: string;
assetPrefix: string;
poweredByHeader: boolean;
canonicalBase: string;
encodedPreviewProps: __ApiPreviewProps;
i18n?: NextConfig['i18n'];
};
export declare function normalizeVercelUrl(req: BaseNextRequest | IncomingMessage, trustQuery: boolean, paramKeys?: string[], pageIsDynamic?: boolean, defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined): void;
export declare function interpolateDynamicPath(pathname: string, params: ParsedUrlQuery, defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined): string;
export declare function getUtils({ page, i18n, basePath, rewrites, pageIsDynamic, trailingSlash, }: {
page: ServerlessHandlerCtx['page'];
i18n?: ServerlessHandlerCtx['i18n'];
basePath: ServerlessHandlerCtx['basePath'];
rewrites: ServerlessHandlerCtx['rewrites'];
pageIsDynamic: ServerlessHandlerCtx['pageIsDynamic'];
trailingSlash?: boolean;
}): {
handleLocale: (req: IncomingMessage, res: ServerResponse, parsedUrl: UrlWithParsedQuery, routeNoAssetPath: string, shouldNotRedirect: boolean) => {
defaultLocale: string;
detectedLocale: string;
routeNoAssetPath: string;
} | undefined;
handleRewrites: (req: BaseNextRequest | IncomingMessage, parsedUrl: UrlWithParsedQuery) => {};
handleBasePath: (req: BaseNextRequest | IncomingMessage, parsedUrl: UrlWithParsedQuery) => void;
defaultRouteRegex: {
namedRegex: string;
routeKeys: {
[named: string]: string;
};
groups: {
[groupName: string]: import("../../../../shared/lib/router/utils/route-regex").Group;
};
re: RegExp;
} | undefined;
dynamicRouteMatcher: RouteMatch | undefined;
defaultRouteMatches: ParsedUrlQuery | undefined;
getParamsFromRouteMatches: (req: BaseNextRequest | IncomingMessage, renderOpts?: any, detectedLocale?: string) => ParsedUrlQuery;
normalizeDynamicRouteParams: (params: ParsedUrlQuery, ignoreOptional?: boolean) => {
params: ParsedUrlQuery;
hasValidParams: boolean;
};
normalizeVercelUrl: (req: BaseNextRequest | IncomingMessage, trustQuery: boolean, paramKeys?: string[]) => void;
interpolateDynamicPath: (pathname: string, params: Record<string, undefined | string | string[]>) => string;
};

View File

@@ -0,0 +1,375 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.normalizeVercelUrl = normalizeVercelUrl;
exports.interpolateDynamicPath = interpolateDynamicPath;
exports.getUtils = getUtils;
exports.vercelHeader = void 0;
var _url = require("url");
var _querystring = require("querystring");
var _normalizeLocalePath = require("../../../../shared/lib/i18n/normalize-locale-path");
var _pathMatch = require("../../../../shared/lib/router/utils/path-match");
var _routeRegex = require("../../../../shared/lib/router/utils/route-regex");
var _routeMatcher = require("../../../../shared/lib/router/utils/route-matcher");
var _prepareDestination = require("../../../../shared/lib/router/utils/prepare-destination");
var _acceptHeader = require("../../../../server/accept-header");
var _detectLocaleCookie = require("../../../../shared/lib/i18n/detect-locale-cookie");
var _detectDomainLocale = require("../../../../shared/lib/i18n/detect-domain-locale");
var _denormalizePagePath = require("../../../../shared/lib/page-path/denormalize-page-path");
var _cookie = _interopRequireDefault(require("next/dist/compiled/cookie"));
var _constants = require("../../../../shared/lib/constants");
var _requestMeta = require("../../../../server/request-meta");
var _removeTrailingSlash = require("../../../../shared/lib/router/utils/remove-trailing-slash");
var _appPaths = require("../../../../shared/lib/router/utils/app-paths");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const vercelHeader = "x-vercel-id";
exports.vercelHeader = vercelHeader;
function normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
const _parsedUrl = (0, _url).parse(req.url, true);
delete _parsedUrl.search;
for (const param of paramKeys || Object.keys(defaultRouteRegex.groups)){
delete _parsedUrl.query[param];
}
req.url = (0, _url).format(_parsedUrl);
}
}
function interpolateDynamicPath(pathname, params, defaultRouteRegex) {
if (!defaultRouteRegex) return pathname;
for (const param of Object.keys(defaultRouteRegex.groups)){
const { optional , repeat } = defaultRouteRegex.groups[param];
let builtParam = `[${repeat ? "..." : ""}${param}]`;
if (optional) {
builtParam = `[${builtParam}]`;
}
const paramIdx = pathname.indexOf(builtParam);
if (paramIdx > -1) {
let paramValue;
const value = params[param];
if (Array.isArray(value)) {
paramValue = value.map((v)=>v && encodeURIComponent(v)).join("/");
} else if (value) {
paramValue = encodeURIComponent(value);
} else {
paramValue = "";
}
pathname = pathname.slice(0, paramIdx) + paramValue + pathname.slice(paramIdx + builtParam.length);
}
}
return pathname;
}
function getUtils({ page , i18n , basePath , rewrites , pageIsDynamic , trailingSlash }) {
let defaultRouteRegex;
let dynamicRouteMatcher;
let defaultRouteMatches;
if (pageIsDynamic) {
defaultRouteRegex = (0, _routeRegex).getNamedRouteRegex(page);
dynamicRouteMatcher = (0, _routeMatcher).getRouteMatcher(defaultRouteRegex);
defaultRouteMatches = dynamicRouteMatcher(page);
}
function handleRewrites(req, parsedUrl) {
const rewriteParams = {};
let fsPathname = parsedUrl.pathname;
const matchesPage = ()=>{
const fsPathnameNoSlash = (0, _removeTrailingSlash).removeTrailingSlash(fsPathname || "");
return fsPathnameNoSlash === (0, _removeTrailingSlash).removeTrailingSlash(page) || (dynamicRouteMatcher == null ? void 0 : dynamicRouteMatcher(fsPathnameNoSlash));
};
const checkRewrite = (rewrite)=>{
const matcher = (0, _pathMatch).getPathMatch(rewrite.source + (trailingSlash ? "(/)?" : ""), {
removeUnnamedParams: true,
strict: true
});
let params = matcher(parsedUrl.pathname);
if ((rewrite.has || rewrite.missing) && params) {
const hasParams = (0, _prepareDestination).matchHas(req, parsedUrl.query, rewrite.has, rewrite.missing);
if (hasParams) {
Object.assign(params, hasParams);
} else {
params = false;
}
}
if (params) {
const { parsedDestination , destQuery } = (0, _prepareDestination).prepareDestination({
appendParamsToQuery: true,
destination: rewrite.destination,
params: params,
query: parsedUrl.query
});
// if the rewrite destination is external break rewrite chain
if (parsedDestination.protocol) {
return true;
}
Object.assign(rewriteParams, destQuery, params);
Object.assign(parsedUrl.query, parsedDestination.query);
delete parsedDestination.query;
Object.assign(parsedUrl, parsedDestination);
fsPathname = parsedUrl.pathname;
if (basePath) {
fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), "") || "/";
}
if (i18n) {
const destLocalePathResult = (0, _normalizeLocalePath).normalizeLocalePath(fsPathname, i18n.locales);
fsPathname = destLocalePathResult.pathname;
parsedUrl.query.nextInternalLocale = destLocalePathResult.detectedLocale || params.nextInternalLocale;
}
if (fsPathname === page) {
return true;
}
if (pageIsDynamic && dynamicRouteMatcher) {
const dynamicParams = dynamicRouteMatcher(fsPathname);
if (dynamicParams) {
parsedUrl.query = {
...parsedUrl.query,
...dynamicParams
};
return true;
}
}
}
return false;
};
for (const rewrite1 of rewrites.beforeFiles || []){
checkRewrite(rewrite1);
}
if (fsPathname !== page) {
let finished = false;
for (const rewrite of rewrites.afterFiles || []){
finished = checkRewrite(rewrite);
if (finished) break;
}
if (!finished && !matchesPage()) {
for (const rewrite of rewrites.fallback || []){
finished = checkRewrite(rewrite);
if (finished) break;
}
}
}
return rewriteParams;
}
function handleBasePath(req, parsedUrl) {
// always strip the basePath if configured since it is required
req.url = req.url.replace(new RegExp(`^${basePath}`), "") || "/";
parsedUrl.pathname = parsedUrl.pathname.replace(new RegExp(`^${basePath}`), "") || "/";
}
function getParamsFromRouteMatches(req, renderOpts, detectedLocale) {
return (0, _routeMatcher).getRouteMatcher(function() {
const { groups , routeKeys } = defaultRouteRegex;
return {
re: {
// Simulate a RegExp match from the \`req.url\` input
exec: (str)=>{
const obj = (0, _querystring).parse(str);
const matchesHasLocale = i18n && detectedLocale && obj["1"] === detectedLocale;
// favor named matches if available
const routeKeyNames = Object.keys(routeKeys || {});
const filterLocaleItem = (val)=>{
if (i18n) {
// locale items can be included in route-matches
// for fallback SSG pages so ensure they are
// filtered
const isCatchAll = Array.isArray(val);
const _val = isCatchAll ? val[0] : val;
if (typeof _val === "string" && i18n.locales.some((item)=>{
if (item.toLowerCase() === _val.toLowerCase()) {
detectedLocale = item;
renderOpts.locale = detectedLocale;
return true;
}
return false;
})) {
// remove the locale item from the match
if (isCatchAll) {
val.splice(0, 1);
}
// the value is only a locale item and
// shouldn't be added
return isCatchAll ? val.length === 0 : true;
}
}
return false;
};
if (routeKeyNames.every((name)=>obj[name])) {
return routeKeyNames.reduce((prev, keyName)=>{
const paramName = routeKeys == null ? void 0 : routeKeys[keyName];
if (paramName && !filterLocaleItem(obj[keyName])) {
prev[groups[paramName].pos] = obj[keyName];
}
return prev;
}, {});
}
return Object.keys(obj).reduce((prev, key)=>{
if (!filterLocaleItem(obj[key])) {
let normalizedKey = key;
if (matchesHasLocale) {
normalizedKey = parseInt(key, 10) - 1 + "";
}
return Object.assign(prev, {
[normalizedKey]: obj[key]
});
}
return prev;
}, {});
}
},
groups
};
}())(req.headers["x-now-route-matches"]);
}
function normalizeDynamicRouteParams(params, ignoreOptional) {
let hasValidParams = true;
if (!defaultRouteRegex) return {
params,
hasValidParams: false
};
params = Object.keys(defaultRouteRegex.groups).reduce((prev, key)=>{
let value = params[key];
if (typeof value === "string") {
value = (0, _appPaths).normalizeRscPath(value, true);
}
if (Array.isArray(value)) {
value = value.map((val)=>{
if (typeof val === "string") {
val = (0, _appPaths).normalizeRscPath(val, true);
}
return val;
});
}
// if the value matches the default value we can't rely
// on the parsed params, this is used to signal if we need
// to parse x-now-route-matches or not
const defaultValue = defaultRouteMatches[key];
const isOptional = defaultRouteRegex.groups[key].optional;
const isDefaultValue = Array.isArray(defaultValue) ? defaultValue.some((defaultVal)=>{
return Array.isArray(value) ? value.some((val)=>val.includes(defaultVal)) : value == null ? void 0 : value.includes(defaultVal);
}) : value == null ? void 0 : value.includes(defaultValue);
if (isDefaultValue || typeof value === "undefined" && !(isOptional && ignoreOptional)) {
hasValidParams = false;
}
// non-provided optional values should be undefined so normalize
// them to undefined
if (isOptional && (!value || Array.isArray(value) && value.length === 1 && // fallback optional catch-all SSG pages have
// [[...paramName]] for the root path on Vercel
(value[0] === "index" || value[0] === `[[...${key}]]`))) {
value = undefined;
delete params[key];
}
// query values from the proxy aren't already split into arrays
// so make sure to normalize catch-all values
if (value && typeof value === "string" && defaultRouteRegex.groups[key].repeat) {
value = value.split("/");
}
if (value) {
prev[key] = value;
}
return prev;
}, {});
return {
params,
hasValidParams
};
}
function handleLocale(req, res, parsedUrl, routeNoAssetPath, shouldNotRedirect) {
if (!i18n) return;
const pathname = parsedUrl.pathname || "/";
let defaultLocale = i18n.defaultLocale;
let detectedLocale = (0, _detectLocaleCookie).detectLocaleCookie(req, i18n.locales);
let acceptPreferredLocale;
try {
acceptPreferredLocale = i18n.localeDetection !== false ? (0, _acceptHeader).acceptLanguage(req.headers["accept-language"], i18n.locales) : detectedLocale;
} catch (_) {
acceptPreferredLocale = detectedLocale;
}
const { host } = req.headers || {};
// remove port from host and remove port if present
const hostname = host && host.split(":")[0].toLowerCase();
const detectedDomain = (0, _detectDomainLocale).detectDomainLocale(i18n.domains, hostname);
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale;
detectedLocale = defaultLocale;
(0, _requestMeta).addRequestMeta(req, "__nextIsLocaleDomain", true);
}
// if not domain specific locale use accept-language preferred
detectedLocale = detectedLocale || acceptPreferredLocale;
let localeDomainRedirect;
const localePathResult = (0, _normalizeLocalePath).normalizeLocalePath(pathname, i18n.locales);
routeNoAssetPath = (0, _normalizeLocalePath).normalizeLocalePath(routeNoAssetPath, i18n.locales).pathname;
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale;
req.url = (0, _url).format({
...parsedUrl,
pathname: localePathResult.pathname
});
(0, _requestMeta).addRequestMeta(req, "__nextStrippedLocale", true);
parsedUrl.pathname = localePathResult.pathname;
}
// If a detected locale is a domain specific locale and we aren't already
// on that domain and path prefix redirect to it to prevent duplicate
// content from multiple domains
if (detectedDomain) {
const localeToCheck = localePathResult.detectedLocale ? detectedLocale : acceptPreferredLocale;
const matchedDomain = (0, _detectDomainLocale).detectDomainLocale(i18n.domains, undefined, localeToCheck);
if (matchedDomain && matchedDomain.domain !== detectedDomain.domain) {
localeDomainRedirect = `http${matchedDomain.http ? "" : "s"}://${matchedDomain.domain}/${localeToCheck === matchedDomain.defaultLocale ? "" : localeToCheck}`;
}
}
const denormalizedPagePath = (0, _denormalizePagePath).denormalizePagePath(pathname);
const detectedDefaultLocale = !detectedLocale || detectedLocale.toLowerCase() === defaultLocale.toLowerCase();
const shouldStripDefaultLocale = false;
// detectedDefaultLocale &&
// denormalizedPagePath.toLowerCase() === \`/\${i18n.defaultLocale.toLowerCase()}\`
const shouldAddLocalePrefix = !detectedDefaultLocale && denormalizedPagePath === "/";
detectedLocale = detectedLocale || i18n.defaultLocale;
if (!shouldNotRedirect && !req.headers[vercelHeader] && i18n.localeDetection !== false && (localeDomainRedirect || shouldAddLocalePrefix || shouldStripDefaultLocale)) {
// set the NEXT_LOCALE cookie when a user visits the default locale
// with the locale prefix so that they aren't redirected back to
// their accept-language preferred locale
if (shouldStripDefaultLocale && acceptPreferredLocale !== defaultLocale) {
const previous = res.getHeader("set-cookie");
res.setHeader("set-cookie", [
...typeof previous === "string" ? [
previous
] : Array.isArray(previous) ? previous : [],
_cookie.default.serialize("NEXT_LOCALE", defaultLocale, {
httpOnly: true,
path: "/"
}),
]);
}
res.setHeader("Location", (0, _url).format({
// make sure to include any query values when redirecting
...parsedUrl,
pathname: localeDomainRedirect ? localeDomainRedirect : shouldStripDefaultLocale ? basePath || "/" : `${basePath}/${detectedLocale}`
}));
res.statusCode = _constants.TEMPORARY_REDIRECT_STATUS;
res.end();
return;
}
detectedLocale = localePathResult.detectedLocale || detectedDomain && detectedDomain.defaultLocale || defaultLocale;
return {
defaultLocale,
detectedLocale,
routeNoAssetPath
};
}
return {
handleLocale,
handleRewrites,
handleBasePath,
defaultRouteRegex,
dynamicRouteMatcher,
defaultRouteMatches,
getParamsFromRouteMatches,
normalizeDynamicRouteParams,
normalizeVercelUrl: (req, trustQuery, paramKeys)=>normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex),
interpolateDynamicPath: (pathname, params)=>interpolateDynamicPath(pathname, params, defaultRouteRegex)
};
}
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long