UNPKG

@serverless-stack/nextjs-lambda

Version:

Provides handlers that can be used in CloudFront Lambda@Edge to deploy next.js applications to the edge

1,381 lines (1,214 loc) 297 kB
'use strict'; var manifest = require('./manifest.json'); var RoutesManifestJson = require('./routes-manifest.json'); var http = require('http'); var Stream = require('stream'); var zlib = require('zlib'); var Url = require('url'); var require$$1 = require('path'); var fs = require('fs'); var crypto = require('crypto'); var require$$0$1 = require('events'); var util = require('util'); var tty = require('tty'); var require$$2 = require('net'); var https = require('https'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n['default'] = e; return Object.freeze(n); } var manifest__default = /*#__PURE__*/_interopDefaultLegacy(manifest); var RoutesManifestJson__default = /*#__PURE__*/_interopDefaultLegacy(RoutesManifestJson); var http__default = /*#__PURE__*/_interopDefaultLegacy(http); var Stream__default = /*#__PURE__*/_interopDefaultLegacy(Stream); var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); var Url__default = /*#__PURE__*/_interopDefaultLegacy(Url); var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); var fs__namespace = /*#__PURE__*/_interopNamespace(fs); var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto); var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); var util__default = /*#__PURE__*/_interopDefaultLegacy(util); var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty); var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); var https__default = /*#__PURE__*/_interopDefaultLegacy(https); /** * Tokenize input string. */ function lexer(str) { var tokens = []; var i = 0; while (i < str.length) { var char = str[i]; if (char === "*" || char === "+" || char === "?") { tokens.push({ type: "MODIFIER", index: i, value: str[i++] }); continue; } if (char === "\\") { tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] }); continue; } if (char === "{") { tokens.push({ type: "OPEN", index: i, value: str[i++] }); continue; } if (char === "}") { tokens.push({ type: "CLOSE", index: i, value: str[i++] }); continue; } if (char === ":") { var name = ""; var j = i + 1; while (j < str.length) { var code = str.charCodeAt(j); if ( // `0-9` (code >= 48 && code <= 57) || // `A-Z` (code >= 65 && code <= 90) || // `a-z` (code >= 97 && code <= 122) || // `_` code === 95) { name += str[j++]; continue; } break; } if (!name) throw new TypeError("Missing parameter name at " + i); tokens.push({ type: "NAME", index: i, value: name }); i = j; continue; } if (char === "(") { var count = 1; var pattern = ""; var j = i + 1; if (str[j] === "?") { throw new TypeError("Pattern cannot start with \"?\" at " + j); } while (j < str.length) { if (str[j] === "\\") { pattern += str[j++] + str[j++]; continue; } if (str[j] === ")") { count--; if (count === 0) { j++; break; } } else if (str[j] === "(") { count++; if (str[j + 1] !== "?") { throw new TypeError("Capturing groups are not allowed at " + j); } } pattern += str[j++]; } if (count) throw new TypeError("Unbalanced pattern at " + i); if (!pattern) throw new TypeError("Missing pattern at " + i); tokens.push({ type: "PATTERN", index: i, value: pattern }); i = j; continue; } tokens.push({ type: "CHAR", index: i, value: str[i++] }); } tokens.push({ type: "END", index: i, value: "" }); return tokens; } /** * Parse a string for the raw tokens. */ function parse$2(str, options) { if (options === void 0) { options = {}; } var tokens = lexer(str); var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a; var defaultPattern = "[^" + escapeString(options.delimiter || "/#?") + "]+?"; var result = []; var key = 0; var i = 0; var path = ""; var tryConsume = function (type) { if (i < tokens.length && tokens[i].type === type) return tokens[i++].value; }; var mustConsume = function (type) { var value = tryConsume(type); if (value !== undefined) return value; var _a = tokens[i], nextType = _a.type, index = _a.index; throw new TypeError("Unexpected " + nextType + " at " + index + ", expected " + type); }; var consumeText = function () { var result = ""; var value; // tslint:disable-next-line while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) { result += value; } return result; }; while (i < tokens.length) { var char = tryConsume("CHAR"); var name = tryConsume("NAME"); var pattern = tryConsume("PATTERN"); if (name || pattern) { var prefix = char || ""; if (prefixes.indexOf(prefix) === -1) { path += prefix; prefix = ""; } if (path) { result.push(path); path = ""; } result.push({ name: name || key++, prefix: prefix, suffix: "", pattern: pattern || defaultPattern, modifier: tryConsume("MODIFIER") || "" }); continue; } var value = char || tryConsume("ESCAPED_CHAR"); if (value) { path += value; continue; } if (path) { result.push(path); path = ""; } var open = tryConsume("OPEN"); if (open) { var prefix = consumeText(); var name_1 = tryConsume("NAME") || ""; var pattern_1 = tryConsume("PATTERN") || ""; var suffix = consumeText(); mustConsume("CLOSE"); result.push({ name: name_1 || (pattern_1 ? key++ : ""), pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1, prefix: prefix, suffix: suffix, modifier: tryConsume("MODIFIER") || "" }); continue; } mustConsume("END"); } return result; } /** * Create path match function from `path-to-regexp` spec. */ function match(str, options) { var keys = []; var re = pathToRegexp(str, keys, options); return regexpToFunction(re, keys, options); } /** * Create a path match function from `path-to-regexp` output. */ function regexpToFunction(re, keys, options) { if (options === void 0) { options = {}; } var _a = options.decode, decode = _a === void 0 ? function (x) { return x; } : _a; return function (pathname) { var m = re.exec(pathname); if (!m) return false; var path = m[0], index = m.index; var params = Object.create(null); var _loop_1 = function (i) { // tslint:disable-next-line if (m[i] === undefined) return "continue"; var key = keys[i - 1]; if (key.modifier === "*" || key.modifier === "+") { params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) { return decode(value, key); }); } else { params[key.name] = decode(m[i], key); } }; for (var i = 1; i < m.length; i++) { _loop_1(i); } return { path: path, index: index, params: params }; }; } /** * Escape a regular expression string. */ function escapeString(str) { return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1"); } /** * Get the flags for a regexp from the options. */ function flags(options) { return options && options.sensitive ? "" : "i"; } /** * Pull out keys from a regexp. */ function regexpToRegexp(path, keys) { if (!keys) return path; var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g; var index = 0; var execResult = groupsRegex.exec(path.source); while (execResult) { keys.push({ // Use parenthesized substring match if available, index otherwise name: execResult[1] || index++, prefix: "", suffix: "", modifier: "", pattern: "" }); execResult = groupsRegex.exec(path.source); } return path; } /** * Transform an array into a regexp. */ function arrayToRegexp(paths, keys, options) { var parts = paths.map(function (path) { return pathToRegexp(path, keys, options).source; }); return new RegExp("(?:" + parts.join("|") + ")", flags(options)); } /** * Create a path regexp from string input. */ function stringToRegexp(path, keys, options) { return tokensToRegexp(parse$2(path, options), keys, options); } /** * Expose a function for taking tokens and returning a RegExp. */ function tokensToRegexp(tokens, keys, options) { if (options === void 0) { options = {}; } var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function (x) { return x; } : _d; var endsWith = "[" + escapeString(options.endsWith || "") + "]|$"; var delimiter = "[" + escapeString(options.delimiter || "/#?") + "]"; var route = start ? "^" : ""; // Iterate over the tokens and create our regexp string. for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) { var token = tokens_1[_i]; if (typeof token === "string") { route += escapeString(encode(token)); } else { var prefix = escapeString(encode(token.prefix)); var suffix = escapeString(encode(token.suffix)); if (token.pattern) { if (keys) keys.push(token); if (prefix || suffix) { if (token.modifier === "+" || token.modifier === "*") { var mod = token.modifier === "*" ? "?" : ""; route += "(?:" + prefix + "((?:" + token.pattern + ")(?:" + suffix + prefix + "(?:" + token.pattern + "))*)" + suffix + ")" + mod; } else { route += "(?:" + prefix + "(" + token.pattern + ")" + suffix + ")" + token.modifier; } } else { route += "(" + token.pattern + ")" + token.modifier; } } else { route += "(?:" + prefix + suffix + ")" + token.modifier; } } } if (end) { if (!strict) route += delimiter + "?"; route += !options.endsWith ? "$" : "(?=" + endsWith + ")"; } else { var endToken = tokens[tokens.length - 1]; var isEndDelimited = typeof endToken === "string" ? delimiter.indexOf(endToken[endToken.length - 1]) > -1 : // tslint:disable-next-line endToken === undefined; if (!strict) { route += "(?:" + delimiter + "(?=" + endsWith + "))?"; } if (!isEndDelimited) { route += "(?=" + delimiter + "|" + endsWith + ")"; } } return new RegExp(route, flags(options)); } /** * Normalize the given path string, returning a regular expression. * * An empty array can be passed in for the keys, which will hold the * placeholder key descriptions. For example, using `/user/:id`, `keys` will * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. */ function pathToRegexp(path, keys, options) { if (path instanceof RegExp) return regexpToRegexp(path, keys); if (Array.isArray(path)) return arrayToRegexp(path, keys, options); return stringToRegexp(path, keys, options); } function addDefaultLocaleToPath(path, routesManifest, forceLocale = null) { if (routesManifest.i18n) { const defaultLocale = forceLocale !== null && forceLocale !== void 0 ? forceLocale : routesManifest.i18n.defaultLocale; const locales = routesManifest.i18n.locales; const basePath = path.startsWith(routesManifest.basePath) ? routesManifest.basePath : ""; // If prefixed with a locale, return that path with normalized locale const pathLowerCase = path.toLowerCase(); for (const locale of locales) { if (pathLowerCase === `${basePath}/${locale}`.toLowerCase() || pathLowerCase.startsWith(`${basePath}/${locale}/`.toLowerCase())) { return path.replace(new RegExp(`${basePath}/${locale}`, "i"), `${basePath}/${forceLocale !== null && forceLocale !== void 0 ? forceLocale : locale}`); } } // Otherwise, prefix with default locale if (path === "/" || path === `${basePath}`) { return `${basePath}/${defaultLocale}`; } else { return path.replace(`${basePath}/`, `${basePath}/${defaultLocale}/`); } } return path; } /** Provides matching capabilities to support custom redirects, rewrites, and headers. */ /** * Match the given path against a source path. * @param path * @param source */ function matchPath(path, source) { const matcher = match(source, { decode: decodeURIComponent }); return matcher(path); } const getCustomHeaders = (uri, routesManifest) => { const localized = addDefaultLocaleToPath(uri, routesManifest); const headers = {}; for (const headerData of routesManifest.headers) { if (!matchPath(localized, headerData.source)) { continue; } for (const { key, value } of headerData.headers) { if (key) { // Header overriding behavior as per: // https://nextjs.org/docs/api-reference/next.config.js/headers headers[key.toLowerCase()] = [{ key, value }]; } } } return headers; }; const setCustomHeaders = (event, routesManifest) => { var _a; const [uri] = ((_a = event.req.url) !== null && _a !== void 0 ? _a : "").split("?"); const headers = getCustomHeaders(uri, routesManifest); for (const [{ key, value }] of Object.values(headers)) { if (key) { event.res.setHeader(key, value); } } }; function getUnauthenticatedResponse(authorizationHeaders, authentication) { var _a; if (authentication && authentication.username && authentication.password) { const validAuth = "Basic " + Buffer.from(authentication.username + ":" + authentication.password).toString("base64"); if (!authorizationHeaders || ((_a = authorizationHeaders[0]) === null || _a === void 0 ? void 0 : _a.value) !== validAuth) { return { isUnauthorized: true, status: 401, statusDescription: "Unauthorized", body: "Unauthorized", headers: { "www-authenticate": [{ key: "WWW-Authenticate", value: "Basic" }] } }; } } } /** * Create a redirect response with the given status code * @param uri * @param querystring * @param statusCode */ function createRedirectResponse(uri, querystring, statusCode) { let location; // Properly join query strings if (querystring) { const [uriPath, uriQuery] = uri.split("?"); location = `${uriPath}?${querystring}${uriQuery ? `&${uriQuery}` : ""}`; } else { location = uri; } const status = statusCode; const statusDescription = http.STATUS_CODES[status]; const refresh = statusCode === 308 ? [ // Required for IE11 compatibility { key: "Refresh", value: `0;url=${location}` } ] : []; const cacheControl = [ { key: "Cache-Control", value: "s-maxage=0" } ]; return { isRedirect: true, status: status, statusDescription: statusDescription || "", headers: { location: [ { key: "Location", value: location } ], refresh: refresh, "cache-control": cacheControl } }; } /** * Get a domain redirect such as redirecting www to non-www domain. * @param request * @param manifest */ function getDomainRedirectPath(request, manifest) { const hostHeaders = request.headers["host"]; if (hostHeaders && hostHeaders.length > 0) { const host = hostHeaders[0].value; const domainRedirects = manifest.domainRedirects; if (domainRedirects && domainRedirects[host]) { return `${domainRedirects[host]}${request.uri}`; } } } const handleAuth = (req, manifest) => { const { headers } = req; return getUnauthenticatedResponse(headers.authorization, manifest.authentication); }; const handleDomainRedirects = (req, manifest) => { const path = getDomainRedirectPath(req, manifest); if (path) { return createRedirectResponse(path, req.querystring, 308); } }; var esm=(()=>{var e={343:(e,t,r)=>{r.r(t);r.d(t,{Observable:()=>Observable,combineLatest:()=>combineLatest,default:()=>l,merge:()=>merge,zip:()=>zip});const n=()=>typeof Symbol==="function";const o=e=>n()&&Boolean(Symbol[e]);const i=e=>o(e)?Symbol[e]:"@@"+e;if(n()&&!o("observable")){Symbol.observable=Symbol("observable");}const s=i("iterator");const u=i("observable");const c=i("species");function getMethod(e,t){let r=e[t];if(r==null)return undefined;if(typeof r!=="function")throw new TypeError(r+" is not a function");return r}function getSpecies(e){let t=e.constructor;if(t!==undefined){t=t[c];if(t===null){t=undefined;}}return t!==undefined?t:Observable}function isObservable(e){return e instanceof Observable}function hostReportError(e){if(hostReportError.log){hostReportError.log(e);}else {setTimeout(()=>{throw e});}}function enqueue(e){Promise.resolve().then(()=>{try{e();}catch(e){hostReportError(e);}});}function cleanupSubscription(e){let t=e._cleanup;if(t===undefined)return;e._cleanup=undefined;if(!t){return}try{if(typeof t==="function"){t();}else {let e=getMethod(t,"unsubscribe");if(e){e.call(t);}}}catch(e){hostReportError(e);}}function closeSubscription(e){e._observer=undefined;e._queue=undefined;e._state="closed";}function flushSubscription(e){let t=e._queue;if(!t){return}e._queue=undefined;e._state="ready";for(let r=0;r<t.length;++r){notifySubscription(e,t[r].type,t[r].value);if(e._state==="closed")break}}function notifySubscription(e,t,r){e._state="running";let n=e._observer;try{let o=getMethod(n,t);switch(t){case"next":if(o)o.call(n,r);break;case"error":closeSubscription(e);if(o)o.call(n,r);else throw r;break;case"complete":closeSubscription(e);if(o)o.call(n);break}}catch(e){hostReportError(e);}if(e._state==="closed")cleanupSubscription(e);else if(e._state==="running")e._state="ready";}function onNotify(e,t,r){if(e._state==="closed")return;if(e._state==="buffering"){e._queue.push({type:t,value:r});return}if(e._state!=="ready"){e._state="buffering";e._queue=[{type:t,value:r}];enqueue(()=>flushSubscription(e));return}notifySubscription(e,t,r);}class Subscription{constructor(e,t){this._cleanup=undefined;this._observer=e;this._queue=undefined;this._state="initializing";let r=new SubscriptionObserver(this);try{this._cleanup=t.call(undefined,r);}catch(e){r.error(e);}if(this._state==="initializing")this._state="ready";}get closed(){return this._state==="closed"}unsubscribe(){if(this._state!=="closed"){closeSubscription(this);cleanupSubscription(this);}}}class SubscriptionObserver{constructor(e){this._subscription=e;}get closed(){return this._subscription._state==="closed"}next(e){onNotify(this._subscription,"next",e);}error(e){onNotify(this._subscription,"error",e);}complete(){onNotify(this._subscription,"complete");}}class Observable{constructor(e){if(!(this instanceof Observable))throw new TypeError("Observable cannot be called as a function");if(typeof e!=="function")throw new TypeError("Observable initializer must be a function");this._subscriber=e;}subscribe(e){if(typeof e!=="object"||e===null){e={next:e,error:arguments[1],complete:arguments[2]};}return new Subscription(e,this._subscriber)}forEach(e){return new Promise((t,r)=>{if(typeof e!=="function"){r(new TypeError(e+" is not a function"));return}function done(){n.unsubscribe();t();}let n=this.subscribe({next(t){try{e(t,done);}catch(e){r(e);n.unsubscribe();}},error:r,complete:t});})}map(e){if(typeof e!=="function")throw new TypeError(e+" is not a function");let t=getSpecies(this);return new t(t=>this.subscribe({next(r){try{r=e(r);}catch(e){return t.error(e)}t.next(r);},error(e){t.error(e);},complete(){t.complete();}}))}filter(e){if(typeof e!=="function")throw new TypeError(e+" is not a function");let t=getSpecies(this);return new t(t=>this.subscribe({next(r){try{if(!e(r))return}catch(e){return t.error(e)}t.next(r);},error(e){t.error(e);},complete(){t.complete();}}))}reduce(e){if(typeof e!=="function")throw new TypeError(e+" is not a function");let t=getSpecies(this);let r=arguments.length>1;let n=false;let o=arguments[1];let i=o;return new t(t=>this.subscribe({next(o){let s=!n;n=true;if(!s||r){try{i=e(i,o);}catch(e){return t.error(e)}}else {i=o;}},error(e){t.error(e);},complete(){if(!n&&!r)return t.error(new TypeError("Cannot reduce an empty sequence"));t.next(i);t.complete();}}))}concat(...e){let t=getSpecies(this);return new t(r=>{let n;let o=0;function startNext(i){n=i.subscribe({next(e){r.next(e);},error(e){r.error(e);},complete(){if(o===e.length){n=undefined;r.complete();}else {startNext(t.from(e[o++]));}}});}startNext(this);return ()=>{if(n){n.unsubscribe();n=undefined;}}})}flatMap(e){if(typeof e!=="function")throw new TypeError(e+" is not a function");let t=getSpecies(this);return new t(r=>{let n=[];let o=this.subscribe({next(o){if(e){try{o=e(o);}catch(e){return r.error(e)}}let i=t.from(o).subscribe({next(e){r.next(e);},error(e){r.error(e);},complete(){let e=n.indexOf(i);if(e>=0)n.splice(e,1);completeIfDone();}});n.push(i);},error(e){r.error(e);},complete(){completeIfDone();}});function completeIfDone(){if(o.closed&&n.length===0)r.complete();}return ()=>{n.forEach(e=>e.unsubscribe());o.unsubscribe();}})}[u](){return this}static from(e){let t=typeof this==="function"?this:Observable;if(e==null)throw new TypeError(e+" is not an object");let r=getMethod(e,u);if(r){let n=r.call(e);if(Object(n)!==n)throw new TypeError(n+" is not an object");if(isObservable(n)&&n.constructor===t)return n;return new t(e=>n.subscribe(e))}if(o("iterator")){r=getMethod(e,s);if(r){return new t(t=>{enqueue(()=>{if(t.closed)return;for(let n of r.call(e)){t.next(n);if(t.closed)return}t.complete();});})}}if(Array.isArray(e)){return new t(t=>{enqueue(()=>{if(t.closed)return;for(let r=0;r<e.length;++r){t.next(e[r]);if(t.closed)return}t.complete();});})}throw new TypeError(e+" is not observable")}static of(...e){let t=typeof this==="function"?this:Observable;return new t(t=>{enqueue(()=>{if(t.closed)return;for(let r=0;r<e.length;++r){t.next(e[r]);if(t.closed)return}t.complete();});})}static get[c](){return this}}if(n()){Object.defineProperty(Observable,Symbol("extensions"),{value:{symbol:u,hostReportError:hostReportError},configurable:true});}function merge(...e){return new Observable(t=>{if(e.length===0)return Observable.from([]);let r=e.length;let n=e.map(e=>Observable.from(e).subscribe({next(e){t.next(e);},error(e){t.error(e);},complete(){if(--r===0)t.complete();}}));return ()=>n.forEach(e=>e.unsubscribe())})}function combineLatest(...e){return new Observable(t=>{if(e.length===0)return Observable.from([]);let r=e.length;let n=new Set;let o=false;let i=e.map(()=>undefined);let s=e.map((s,u)=>Observable.from(s).subscribe({next(r){i[u]=r;if(!o){n.add(u);if(n.size!==e.length)return;n=null;o=true;}t.next(Array.from(i));},error(e){t.error(e);},complete(){if(--r===0)t.complete();}}));return ()=>s.forEach(e=>e.unsubscribe())})}function zip(...e){return new Observable(t=>{if(e.length===0)return Observable.from([]);let r=e.map(()=>[]);function done(){return r.some((e,t)=>e.length===0&&n[t].closed)}let n=e.map((e,n)=>Observable.from(e).subscribe({next(e){r[n].push(e);if(r.every(e=>e.length>0)){t.next(r.map(e=>e.shift()));if(done())t.complete();}},error(e){t.error(e);},complete(){if(done())t.complete();}}));return ()=>n.forEach(e=>e.unsubscribe())})}const l=Observable;}};var t={};function __nccwpck_require__(r){if(t[r]){return t[r].exports}var n=t[r]={exports:{}};var o=true;try{e[r](n,n.exports,__nccwpck_require__);o=false;}finally{if(o)delete t[r];}return n.exports}(()=>{__nccwpck_require__.d=((e,t)=>{for(var r in t){if(__nccwpck_require__.o(t,r)&&!__nccwpck_require__.o(e,r)){Object.defineProperty(e,r,{enumerable:true,get:t[r]});}}});})();(()=>{__nccwpck_require__.o=((e,t)=>Object.prototype.hasOwnProperty.call(e,t));})();(()=>{__nccwpck_require__.r=(e=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});}Object.defineProperty(e,"__esModule",{value:true});});})();__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(343)})(); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getAugmentedNamespace(n) { if (n.__esModule) return n; var a = Object.defineProperty({}, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } function createCommonjsModule(fn) { var module = { exports: {} }; return fn(module, module.exports), module.exports; } createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.SERVER_DIRECTORY = exports.PAGES_MANIFEST = exports.SERVER_PROPS_ID = exports.CLIENT_STATIC_FILES_RUNTIME_WEBPACK = exports.PERMANENT_REDIRECT_STATUS = exports.SERVER_FILES_MANIFEST = exports.STATIC_PROPS_ID = exports.BUILD_MANIFEST = exports.BLOCKED_PAGES = exports.STATIC_STATUS_PAGES = exports.PRERENDER_MANIFEST = exports.DEV_CLIENT_PAGES_MANIFEST = exports.OPTIMIZED_FONT_PROVIDERS = exports.TEMPORARY_REDIRECT_STATUS = exports.SERVERLESS_DIRECTORY = exports.EXPORT_MARKER = exports.GOOGLE_FONT_PROVIDER = exports.PHASE_PRODUCTION_BUILD = exports.CLIENT_STATIC_FILES_RUNTIME_MAIN = exports.BUILD_ID_FILE = exports.CONFIG_FILE = exports.CLIENT_STATIC_FILES_RUNTIME = exports.PHASE_PRODUCTION_SERVER = exports.EXPORT_DETAIL = exports.IMAGES_MANIFEST = exports.CLIENT_STATIC_FILES_RUNTIME_AMP = exports.CLIENT_PUBLIC_FILES_PATH = exports.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = exports.STRING_LITERAL_DROP_BUNDLE = exports.TRACE_OUTPUT_VERSION = exports.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = exports.FONT_MANIFEST = exports.REACT_LOADABLE_MANIFEST = exports.ROUTES_MANIFEST = exports.CLIENT_STATIC_FILES_PATH = exports.BODY_RENDER_TARGET = exports.PHASE_EXPORT = exports.PHASE_DEVELOPMENT_SERVER = void 0; const PHASE_EXPORT = 'phase-export'; exports.PHASE_EXPORT = PHASE_EXPORT; const PHASE_PRODUCTION_BUILD = 'phase-production-build'; exports.PHASE_PRODUCTION_BUILD = PHASE_PRODUCTION_BUILD; const PHASE_PRODUCTION_SERVER = 'phase-production-server'; exports.PHASE_PRODUCTION_SERVER = PHASE_PRODUCTION_SERVER; const PHASE_DEVELOPMENT_SERVER = 'phase-development-server'; exports.PHASE_DEVELOPMENT_SERVER = PHASE_DEVELOPMENT_SERVER; const PAGES_MANIFEST = 'pages-manifest.json'; exports.PAGES_MANIFEST = PAGES_MANIFEST; const BUILD_MANIFEST = 'build-manifest.json'; exports.BUILD_MANIFEST = BUILD_MANIFEST; const EXPORT_MARKER = 'export-marker.json'; exports.EXPORT_MARKER = EXPORT_MARKER; const EXPORT_DETAIL = 'export-detail.json'; exports.EXPORT_DETAIL = EXPORT_DETAIL; const PRERENDER_MANIFEST = 'prerender-manifest.json'; exports.PRERENDER_MANIFEST = PRERENDER_MANIFEST; const ROUTES_MANIFEST = 'routes-manifest.json'; exports.ROUTES_MANIFEST = ROUTES_MANIFEST; const IMAGES_MANIFEST = 'images-manifest.json'; exports.IMAGES_MANIFEST = IMAGES_MANIFEST; const SERVER_FILES_MANIFEST = 'required-server-files.json'; exports.SERVER_FILES_MANIFEST = SERVER_FILES_MANIFEST; const DEV_CLIENT_PAGES_MANIFEST = '_devPagesManifest.json'; exports.DEV_CLIENT_PAGES_MANIFEST = DEV_CLIENT_PAGES_MANIFEST; const REACT_LOADABLE_MANIFEST = 'react-loadable-manifest.json'; exports.REACT_LOADABLE_MANIFEST = REACT_LOADABLE_MANIFEST; const FONT_MANIFEST = 'font-manifest.json'; exports.FONT_MANIFEST = FONT_MANIFEST; const SERVER_DIRECTORY = 'server'; exports.SERVER_DIRECTORY = SERVER_DIRECTORY; const SERVERLESS_DIRECTORY = 'serverless'; exports.SERVERLESS_DIRECTORY = SERVERLESS_DIRECTORY; const CONFIG_FILE = 'next.config.js'; exports.CONFIG_FILE = CONFIG_FILE; const BUILD_ID_FILE = 'BUILD_ID'; exports.BUILD_ID_FILE = BUILD_ID_FILE; const BLOCKED_PAGES = [ '/_document', '/_app', '/_error' ]; exports.BLOCKED_PAGES = BLOCKED_PAGES; const CLIENT_PUBLIC_FILES_PATH = 'public'; exports.CLIENT_PUBLIC_FILES_PATH = CLIENT_PUBLIC_FILES_PATH; const CLIENT_STATIC_FILES_PATH = 'static'; exports.CLIENT_STATIC_FILES_PATH = CLIENT_STATIC_FILES_PATH; const CLIENT_STATIC_FILES_RUNTIME = 'runtime'; exports.CLIENT_STATIC_FILES_RUNTIME = CLIENT_STATIC_FILES_RUNTIME; const BODY_RENDER_TARGET = '__NEXT_BODY_RENDER_TARGET__'; exports.BODY_RENDER_TARGET = BODY_RENDER_TARGET; const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'; exports.STRING_LITERAL_DROP_BUNDLE = STRING_LITERAL_DROP_BUNDLE; const CLIENT_STATIC_FILES_RUNTIME_MAIN = `main`; exports.CLIENT_STATIC_FILES_RUNTIME_MAIN = CLIENT_STATIC_FILES_RUNTIME_MAIN; const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `react-refresh`; exports.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH; const CLIENT_STATIC_FILES_RUNTIME_AMP = `amp`; exports.CLIENT_STATIC_FILES_RUNTIME_AMP = CLIENT_STATIC_FILES_RUNTIME_AMP; const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `webpack`; exports.CLIENT_STATIC_FILES_RUNTIME_WEBPACK = CLIENT_STATIC_FILES_RUNTIME_WEBPACK; const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(`polyfills`); exports.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL; const TEMPORARY_REDIRECT_STATUS = 307; exports.TEMPORARY_REDIRECT_STATUS = TEMPORARY_REDIRECT_STATUS; const PERMANENT_REDIRECT_STATUS = 308; exports.PERMANENT_REDIRECT_STATUS = PERMANENT_REDIRECT_STATUS; const STATIC_PROPS_ID = '__N_SSG'; exports.STATIC_PROPS_ID = STATIC_PROPS_ID; const SERVER_PROPS_ID = '__N_SSP'; exports.SERVER_PROPS_ID = SERVER_PROPS_ID; const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/css'; exports.GOOGLE_FONT_PROVIDER = GOOGLE_FONT_PROVIDER; const OPTIMIZED_FONT_PROVIDERS = [ { url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' }, { url: 'https://use.typekit.net', preconnect: 'https://use.typekit.net' }, ]; exports.OPTIMIZED_FONT_PROVIDERS = OPTIMIZED_FONT_PROVIDERS; const STATIC_STATUS_PAGES = [ '/500' ]; exports.STATIC_STATUS_PAGES = STATIC_STATUS_PAGES; const TRACE_OUTPUT_VERSION = 1; exports.TRACE_OUTPUT_VERSION = TRACE_OUTPUT_VERSION; }); _interopRequireDefault(esm); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const specialNodeHeaders = [ "age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "user-agent" ]; const readOnlyCloudFrontHeaders = { "accept-encoding": true, "content-length": true, "if-modified-since": true, "if-none-match": true, "if-range": true, "if-unmodified-since": true, "transfer-encoding": true, via: true }; const HttpStatusCodes = { 202: "Accepted", 502: "Bad Gateway", 400: "Bad Request", 409: "Conflict", 100: "Continue", 201: "Created", 417: "Expectation Failed", 424: "Failed Dependency", 403: "Forbidden", 504: "Gateway Timeout", 410: "Gone", 505: "HTTP Version Not Supported", 418: "I'm a teapot", 419: "Insufficient Space on Resource", 507: "Insufficient Storage", 500: "Server Error", 411: "Length Required", 423: "Locked", 420: "Method Failure", 405: "Method Not Allowed", 301: "Moved Permanently", 302: "Moved Temporarily", 207: "Multi-Status", 300: "Multiple Choices", 511: "Network Authentication Required", 204: "No Content", 203: "Non Authoritative Information", 406: "Not Acceptable", 404: "Not Found", 501: "Not Implemented", 304: "Not Modified", 200: "OK", 206: "Partial Content", 402: "Payment Required", 308: "Permanent Redirect", 412: "Precondition Failed", 428: "Precondition Required", 102: "Processing", 407: "Proxy Authentication Required", 431: "Request Header Fields Too Large", 408: "Request Timeout", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 416: "Requested Range Not Satisfiable", 205: "Reset Content", 303: "See Other", 503: "Service Unavailable", 101: "Switching Protocols", 307: "Temporary Redirect", 429: "Too Many Requests", 401: "Unauthorized", 422: "Unprocessable Entity", 415: "Unsupported Media Type", 305: "Use Proxy" }; const toCloudFrontHeaders = (headers, headerNames, originalHeaders) => { const result = {}; Object.entries(originalHeaders).forEach(([headerName, headerValue]) => { result[headerName.toLowerCase()] = headerValue; }); Object.entries(headers).forEach(([headerName, headerValue]) => { const headerKey = headerName.toLowerCase(); headerName = headerNames[headerKey] || headerName; if (readOnlyCloudFrontHeaders[headerKey]) { return; } result[headerKey] = []; if (headerValue instanceof Array) { headerValue.forEach((val) => { result[headerKey].push({ key: headerName, value: val.toString() }); }); } else { result[headerKey].push({ key: headerName, value: headerValue.toString() }); } }); return result; }; const isGzipSupported = (headers) => { let gz = false; const ae = headers["accept-encoding"]; if (ae) { for (let i = 0; i < ae.length; i++) { const { value } = ae[i]; const bits = value.split(",").map((x) => x.split(";")[0].trim()); if (bits.indexOf("gzip") !== -1) { gz = true; } } } return gz; }; const defaultOptions = { enableHTTPCompression: false }; const handler$1 = ( event, { enableHTTPCompression, rewrittenUri } = defaultOptions ) => { const { request: cfRequest, response: cfResponse = { headers: {} } } = event; const response = { headers: {} }; const newStream = new Stream__default['default'].Readable(); const req = Object.assign(newStream, http__default['default'].IncomingMessage.prototype); req.url = rewrittenUri || cfRequest.uri; req.method = cfRequest.method; req.rawHeaders = []; req.headers = {}; req.connection = {}; if (cfRequest.querystring) { req.url = req.url + `?` + cfRequest.querystring; } const headers = cfRequest.headers || {}; for (const lowercaseKey of Object.keys(headers)) { const headerKeyValPairs = headers[lowercaseKey]; headerKeyValPairs.forEach((keyVal) => { req.rawHeaders.push(keyVal.key); req.rawHeaders.push(keyVal.value); }); req.headers[lowercaseKey] = headerKeyValPairs[0].value; } req.getHeader = (name) => { return req.headers[name.toLowerCase()]; }; req.getHeaders = () => { return req.headers; }; if (cfRequest.body && cfRequest.body.data) { req.push( cfRequest.body.data, cfRequest.body.encoding ? "base64" : undefined ); } req.push(null); const res = new Stream__default['default'](); res.finished = false; Object.defineProperty(res, "statusCode", { get() { return response.status; }, set(statusCode) { response.status = statusCode; response.statusDescription = HttpStatusCodes[statusCode]; } }); res.headers = {}; const headerNames = {}; res.writeHead = (status, headers) => { response.status = status; response.statusDescription = HttpStatusCodes[status]; if (headers) { res.headers = Object.assign(res.headers, headers); } return res; }; res.write = (chunk) => { if (!response.body) { response.body = Buffer.from(""); } response.body = Buffer.concat([ response.body, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) ]); }; let shouldGzip = enableHTTPCompression && isGzipSupported(headers); const responsePromise = new Promise((resolve) => { res.end = (text) => { if (res.finished === true) { return; } res.finished = true; if (text) res.write(text); if (!res.statusCode) { res.statusCode = 200; } if (response.body) { response.bodyEncoding = "base64"; response.body = shouldGzip ? zlib__default['default'].gzipSync(response.body).toString("base64") : Buffer.from(response.body).toString("base64"); } response.headers = toCloudFrontHeaders( res.headers, headerNames, cfResponse.headers ); if (shouldGzip) { response.headers["content-encoding"] = [ { key: "Content-Encoding", value: "gzip" } ]; } resolve(response); }; }); res.setHeader = (name, value) => { res.headers[name.toLowerCase()] = value; headerNames[name.toLowerCase()] = name; }; res.removeHeader = (name) => { delete res.headers[name.toLowerCase()]; }; res.getHeader = (name) => { return res.headers[name.toLowerCase()]; }; res.getHeaders = () => { return res.headers; }; res.hasHeader = (name) => { return !!res.getHeader(name); }; return { req, res, responsePromise }; }; handler$1.SPECIAL_NODE_HEADERS = specialNodeHeaders; var nextAwsCloudfront = handler$1; var stringify$1 = function (...args) { try { return JSON.stringify.apply(null, args); } catch (err) { return '[Cannot display object: ' + err.message + ']'; } }; var error = createCommonjsModule(function (module, exports) { module.exports = class extends Error { constructor(args) { const msgs = args .filter((arg) => arg !== '') .map((arg) => { return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : stringify$1(arg); }); super(msgs.join(' ') || 'Unknown error'); if (typeof Error.captureStackTrace === 'function') { // $lab:coverage:ignore$ Error.captureStackTrace(this, exports.assert); } } }; }); var assert$1 = function (condition, ...args) { if (condition) { return; } if (args.length === 1 && args[0] instanceof Error) { throw args[0]; } throw new error(args); }; const internals$9 = {}; var reach$1 = function (obj, chain, options) { if (chain === false || chain === null || chain === undefined) { return obj; } options = options || {}; if (typeof options === 'string') { options = { separator: options }; } const isChainArray = Array.isArray(chain); assert$1(!isChainArray || !options.separator, 'Separator option no valid for array-based chain'); const path = isChainArray ? chain : chain.split(options.separator || '.'); let ref = obj; for (let i = 0; i < path.length; ++i) { let key = path[i]; const type = options.iterables && internals$9.iterables(ref); if (Array.isArray(ref) || type === 'set') { const number = Number(key); if (Number.isInteger(number)) { key = number < 0 ? ref.length + number : number; } } if (!ref || typeof ref === 'function' && options.functions === false || // Defaults to true !type && ref[key] === undefined) { assert$1(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain); assert$1(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain); ref = options.default; break; } if (!type) { ref = ref[key]; } else if (type === 'set') { ref = [...ref][key]; } else { // type === 'map' ref = ref.get(key); } } return ref; }; internals$9.iterables = function (ref) { if (ref instanceof Set) { return 'set'; } if (ref instanceof Map) { return 'map'; } }; var types = createCommonjsModule(function (module, exports) { const internals = {}; exports = module.exports = { array: Array.prototype, buffer: Buffer && Buffer.prototype, // $lab:coverage:ignore$ date: Date.prototype, error: Error.prototype, generic: Object.prototype, map: Map.prototype, promise: Promise.prototype, regex: RegExp.prototype, set: Set.prototype, weakMap: WeakMap.prototype, weakSet: WeakSet.prototype }; internals.typeMap = new Map([ ['[object Error]', exports.error], ['[object Map]', exports.map], ['[object Promise]', exports.promise], ['[object Set]', exports.set], ['[object WeakMap]', exports.weakMap], ['[object WeakSet]', exports.weakSet] ]); exports.getInternalProto = function (obj) { if (Array.isArray(obj)) { return exports.array; } if (Buffer && obj instanceof Buffer) { // $lab:coverage:ignore$ return exports.buffer; } if (obj instanceof Date) { return exports.date; } if (obj instanceof RegExp) { return exports.regex; } if (obj instanceof Error) { return exports.error; } const objName = Object.prototype.toString.call(obj); return internals.typeMap.get(objName) || exports.generic; }; }); var keys = function (obj, options = {}) { return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true }; var utils = { keys: keys }; const internals$8 = { needsProtoHack: new Set([types.set, types.map, types.weakSet, types.weakMap]) }; var clone$2 = internals$8.clone = function (obj, options = {}, _seen = null) { if (typeof obj !== 'object' || obj === null) { return obj; } let clone = internals$8.clone; let seen = _seen; if (options.shallow) { if (options.shallow !== true) { return internals$8.cloneWithShallow(obj, options); } clone = (value) => value; } else if (seen) { const lookup = seen.get(obj); if (lookup) { return lookup; } } else { seen = new Map(); } // Built-in object types const baseProto = types.getInternalProto(obj); if (baseProto === types.buffer) { return Buffer && Buffer.from(obj); // $lab:coverage:ignore$ } if (baseProto === types.date) { return new Date(obj.getTime()); } if (baseProto === types.regex) { return new RegExp(obj); } // Generic objects const newObj = internals$8.base(obj, baseProto, options); if (newObj === obj) { return obj; } if (seen) { seen.set(obj, newObj); // Set seen, since obj could recurse } if (baseProto === types.set) { for (const value of obj) { newObj.add(clone(value, options, seen)); } } else if (baseProto === types.map) { for (const [key, value] of obj) { newObj.set(key, clone(value, options, seen)); } } const keys = utils.keys(obj, options); for (const key of keys) { if (key === '__proto__') { continue; } if (baseProto === types.array && key === 'length') { newObj.length = obj.length; continue; } const descriptor = Object.getOwnPropertyDescriptor(obj, key); if (descriptor) { if (descriptor.get || descriptor.set) { Object.defineProperty(newObj, key, descriptor); } else if (descriptor.enumerable) { newObj[key] = clone(obj[key], options, seen); } else { Object.defineProperty(newObj, key, { enumerable: false, writable: true, configurable: true, value: clone(obj[key], options, seen) }); } } else { Object.defineProperty(newObj, key, { enumerable: true, writable: true, configurable: true, value: clone(obj[key], options, seen) }); } } return newObj; }; internals$8.cloneWithShallow = function (source, options) { const keys = options.shallow; options = Object.assign({}, options); options.shallow = false; const seen = new Map(); for (const key of keys) { const ref = reach$1(source, key); if (typeof ref === 'object' || typeof ref === 'function') { seen.set(ref, ref); } } return internals$8.clone(source, options, seen); }; internals$8.base = function (obj, baseProto, options) { if (options.prototype === false) { // Defaults to true if (internals$8.needsProtoHack.has(baseProto)) { return new baseProto.constructor(); } return baseProto === types.array ? [] : {}; } const proto = Object.getPrototypeOf(obj); if (proto && proto.isImmutable) { return obj; } if (baseProto === types.array) { const newObj = []; if (proto !== baseProto) { Object.setPrototypeOf(newObj, proto); } return newObj; } if (internals$8.needsProtoHack.has(baseProto)) { const newObj = new proto.constructor(); if (proto !== baseProto) { Object.setPrototypeOf(newObj, proto); } return newObj; } return Object.create(proto); }; const internals$7 = {}; var merge$1 = internals$7.merge = function (target, source, options) { assert$1(target && typeof target === 'object', 'Invalid target value: must be an object'); assert$1(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object'); if (!source) { return target; } options = Object.assign({ nullOverride: true, mergeArrays: true }, options); if (Array.isArray(source)) { assert$1(Array.isArray(target), 'Cannot merge array onto an object'); if (!options.mergeArrays) { target.length = 0; // Must not change target assignment } for (let i = 0; i < source.length; ++i) { target.push(clone$2(source[i], { symbols: options.symbols })); } return target; } const keys = utils.keys(source, options); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (key === '__proto__' || !Object.prototype.propertyIsEnumerable.call(source, key)) { continue; } const value = source[key]; if (value && typeof value === 'object') { if (target[key] === value) { continue; // Can occur for shallow merges } if (!target[key] || ty