@serverless-stack/nextjs-lambda
Version:
Provides handlers that can be used in CloudFront Lambda@Edge to deploy next.js applications to the edge
2 lines (1 loc) • 17.8 kB
JavaScript
var e=require("stream"),t=require("http"),r=require("url"),o=require("https"),n=require("zlib");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=s(e),u=s(t),a=s(r),l=s(o),c=s(n);const f=i.default.Readable,d=Symbol("buffer"),h=Symbol("type");class p{constructor(){this[h]="";const e=arguments[0],t=arguments[1],r=[];let o=0;if(e){const t=e,n=Number(t.length);for(let e=0;e<n;e++){const n=t[e];let s;s=n instanceof Buffer?n:ArrayBuffer.isView(n)?Buffer.from(n.buffer,n.byteOffset,n.byteLength):n instanceof ArrayBuffer?Buffer.from(n):n instanceof p?n[d]:Buffer.from("string"==typeof n?n:String(n)),o+=s.length,r.push(s)}}this[d]=Buffer.concat(r);let n=t&&void 0!==t.type&&String(t.type).toLowerCase();n&&!/[^\u0020-\u007E]/.test(n)&&(this[h]=n)}get size(){return this[d].length}get type(){return this[h]}text(){return Promise.resolve(this[d].toString())}arrayBuffer(){const e=this[d],t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return Promise.resolve(t)}stream(){const e=new f;return e._read=function(){},e.push(this[d]),e.push(null),e}toString(){return"[object Blob]"}slice(){const e=this.size,t=arguments[0],r=arguments[1];let o,n;o=void 0===t?0:t<0?Math.max(e+t,0):Math.min(t,e),n=void 0===r?e:r<0?Math.max(e+r,0):Math.min(r,e);const s=Math.max(n-o,0),i=this[d].slice(o,o+s),u=new p([],{type:arguments[2]});return u[d]=i,u}}function b(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}let y;Object.defineProperties(p.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}}),Object.defineProperty(p.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0}),b.prototype=Object.create(Error.prototype),b.prototype.constructor=b,b.prototype.name="FetchError";try{y=require("encoding").convert}catch(e){}const m=Symbol("Body internals"),g=i.default.PassThrough;function w(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=r.size;let n=void 0===o?0:o;var s=r.timeout;let u=void 0===s?0:s;null==e?e=null:T(e)?e=Buffer.from(e.toString()):S(e)||Buffer.isBuffer(e)||("[object ArrayBuffer]"===Object.prototype.toString.call(e)?e=Buffer.from(e):ArrayBuffer.isView(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof i.default||(e=Buffer.from(String(e)))),this[m]={body:e,disturbed:!1,error:null},this.size=n,this.timeout=u,e instanceof i.default&&e.on("error",(function(e){const r="AbortError"===e.name?e:new b(`Invalid response body while trying to fetch ${t.url}: ${e.message}`,"system",e);t[m].error=r}))}function v(){var e=this;if(this[m].disturbed)return w.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[m].disturbed=!0,this[m].error)return w.Promise.reject(this[m].error);let t=this.body;if(null===t)return w.Promise.resolve(Buffer.alloc(0));if(S(t)&&(t=t.stream()),Buffer.isBuffer(t))return w.Promise.resolve(t);if(!(t instanceof i.default))return w.Promise.resolve(Buffer.alloc(0));let r=[],o=0,n=!1;return new w.Promise((function(s,i){let u;e.timeout&&(u=setTimeout((function(){n=!0,i(new b(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))}),e.timeout)),t.on("error",(function(t){"AbortError"===t.name?(n=!0,i(t)):i(new b(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,"system",t))})),t.on("data",(function(t){if(!n&&null!==t){if(e.size&&o+t.length>e.size)return n=!0,void i(new b(`content size at ${e.url} over limit: ${e.size}`,"max-size"));o+=t.length,r.push(t)}})),t.on("end",(function(){if(!n){clearTimeout(u);try{s(Buffer.concat(r,o))}catch(t){i(new b(`Could not create Buffer from response body for ${e.url}: ${t.message}`,"system",t))}}}))}))}function T(e){return"object"==typeof e&&"function"==typeof e.append&&"function"==typeof e.delete&&"function"==typeof e.get&&"function"==typeof e.getAll&&"function"==typeof e.has&&"function"==typeof e.set&&("URLSearchParams"===e.constructor.name||"[object URLSearchParams]"===Object.prototype.toString.call(e)||"function"==typeof e.sort)}function S(e){return"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}function j(e){let t,r,o=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof i.default&&"function"!=typeof o.getBoundary&&(t=new g,r=new g,o.pipe(t),o.pipe(r),e[m].body=t,o=r),o}function O(e){return null===e?null:"string"==typeof e?"text/plain;charset=UTF-8":T(e)?"application/x-www-form-urlencoded;charset=UTF-8":S(e)?e.type||null:Buffer.isBuffer(e)||"[object ArrayBuffer]"===Object.prototype.toString.call(e)||ArrayBuffer.isView(e)?null:"function"==typeof e.getBoundary?`multipart/form-data;boundary=${e.getBoundary()}`:e instanceof i.default?null:"text/plain;charset=UTF-8"}function x(e){const t=e.body;return null===t?0:S(t)?t.size:Buffer.isBuffer(t)?t.length:t&&"function"==typeof t.getLengthSync&&(t._lengthRetrievers&&0==t._lengthRetrievers.length||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}w.prototype={get body(){return this[m].body},get bodyUsed(){return this[m].disturbed},arrayBuffer(){return v.call(this).then((function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}))},blob(){let e=this.headers&&this.headers.get("content-type")||"";return v.call(this).then((function(t){return Object.assign(new p([],{type:e.toLowerCase()}),{[d]:t})}))},json(){var e=this;return v.call(this).then((function(t){try{return JSON.parse(t.toString())}catch(t){return w.Promise.reject(new b(`invalid json response body at ${e.url} reason: ${t.message}`,"invalid-json"))}}))},text(){return v.call(this).then((function(e){return e.toString()}))},buffer(){return v.call(this)},textConverted(){var e=this;return v.call(this).then((function(t){return function(e,t){if("function"!=typeof y)throw new Error("The package `encoding` must be installed to use the textConverted() function");const r=t.get("content-type");let o,n,s="utf-8";r&&(o=/charset=([^;]*)/i.exec(r));n=e.slice(0,1024).toString(),!o&&n&&(o=/<meta.+?charset=(['"])(.+?)\1/i.exec(n));!o&&n&&(o=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(n),o||(o=/<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(n),o&&o.pop()),o&&(o=/charset=(.*)/i.exec(o.pop())));!o&&n&&(o=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(n));o&&(s=o.pop(),"gb2312"!==s&&"gbk"!==s||(s="gb18030"));return y(e,"UTF-8",s).toString()}(t,e.headers)}))}},Object.defineProperties(w.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}}),w.mixIn=function(e){for(const t of Object.getOwnPropertyNames(w.prototype))if(!(t in e)){const r=Object.getOwnPropertyDescriptor(w.prototype,t);Object.defineProperty(e,t,r)}},w.Promise=global.Promise;const E=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,P=/[^\t\x20-\x7e\x80-\xff]/;function B(e){if(e=`${e}`,E.test(e)||""===e)throw new TypeError(`${e} is not a legal HTTP header name`)}function $(e){if(e=`${e}`,P.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function C(e,t){t=t.toLowerCase();for(const r in e)if(r.toLowerCase()===t)return r}const L=Symbol("map");class A{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;if(this[L]=Object.create(null),e instanceof A){const t=e.raw(),r=Object.keys(t);for(const e of r)for(const r of t[e])this.append(e,r)}else if(null==e);else{if("object"!=typeof e)throw new TypeError("Provided initializer must be an object");{const t=e[Symbol.iterator];if(null!=t){if("function"!=typeof t)throw new TypeError("Header pairs must be iterable");const r=[];for(const t of e){if("object"!=typeof t||"function"!=typeof t[Symbol.iterator])throw new TypeError("Each header pair must be iterable");r.push(Array.from(t))}for(const e of r){if(2!==e.length)throw new TypeError("Each header pair must be a name/value tuple");this.append(e[0],e[1])}}else for(const t of Object.keys(e)){const r=e[t];this.append(t,r)}}}}get(e){B(e=`${e}`);const t=C(this[L],e);return void 0===t?null:this[L][t].join(", ")}forEach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,r=z(this),o=0;for(;o<r.length;){var n=r[o];const s=n[0],i=n[1];e.call(t,i,s,this),r=z(this),o++}}set(e,t){t=`${t}`,B(e=`${e}`),$(t);const r=C(this[L],e);this[L][void 0!==r?r:e]=[t]}append(e,t){t=`${t}`,B(e=`${e}`),$(t);const r=C(this[L],e);void 0!==r?this[L][r].push(t):this[L][e]=[t]}has(e){return B(e=`${e}`),void 0!==C(this[L],e)}delete(e){B(e=`${e}`);const t=C(this[L],e);void 0!==t&&delete this[L][t]}raw(){return this[L]}keys(){return R(this,"key")}values(){return R(this,"value")}[Symbol.iterator](){return R(this,"key+value")}}function z(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"key+value";const r=Object.keys(e[L]).sort();return r.map("key"===t?function(e){return e.toLowerCase()}:"value"===t?function(t){return e[L][t].join(", ")}:function(t){return[t.toLowerCase(),e[L][t].join(", ")]})}A.prototype.entries=A.prototype[Symbol.iterator],Object.defineProperty(A.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(A.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});const k=Symbol("internal");function R(e,t){const r=Object.create(U);return r[k]={target:e,kind:t,index:0},r}const U=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==U)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[k];const t=e.target,r=e.kind,o=e.index,n=z(t,r);return o>=n.length?{value:void 0,done:!0}:(this[k].index=o+1,{value:n[o],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));function q(e){const t=Object.assign({__proto__:null},e[L]),r=C(e[L],"Host");return void 0!==r&&(t[r]=t[r][0]),t}Object.defineProperty(U,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});const H=Symbol("Response internals"),_=u.default.STATUS_CODES;class F{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w.call(this,e,t);const r=t.status||200,o=new A(t.headers);if(null!=e&&!o.has("Content-Type")){const t=O(e);t&&o.append("Content-Type",t)}this[H]={url:t.url,status:r,statusText:t.statusText||_[r],headers:o,counter:t.counter}}get url(){return this[H].url||""}get status(){return this[H].status}get ok(){return this[H].status>=200&&this[H].status<300}get redirected(){return this[H].counter>0}get statusText(){return this[H].statusText}get headers(){return this[H].headers}clone(){return new F(j(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected})}}w.mixIn(F.prototype),Object.defineProperties(F.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}}),Object.defineProperty(F.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});const I=Symbol("Request internals"),D=a.default.parse,M=a.default.format,G="destroy"in i.default.Readable.prototype;function N(e){return"object"==typeof e&&"object"==typeof e[I]}class V{constructor(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};N(e)?t=D(e.url):(t=e&&e.href?D(e.href):D(`${e}`),e={});let o=r.method||e.method||"GET";if(o=o.toUpperCase(),(null!=r.body||N(e)&&null!==e.body)&&("GET"===o||"HEAD"===o))throw new TypeError("Request with GET/HEAD method cannot have body");let n=null!=r.body?r.body:N(e)&&null!==e.body?j(e):null;w.call(this,n,{timeout:r.timeout||e.timeout||0,size:r.size||e.size||0});const s=new A(r.headers||e.headers||{});if(null!=n&&!s.has("Content-Type")){const e=O(n);e&&s.append("Content-Type",e)}let i=N(e)?e.signal:null;if("signal"in r&&(i=r.signal),null!=i&&!function(e){const t=e&&"object"==typeof e&&Object.getPrototypeOf(e);return!(!t||"AbortSignal"!==t.constructor.name)}(i))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[I]={method:o,redirect:r.redirect||e.redirect||"follow",headers:s,parsedURL:t,signal:i},this.follow=void 0!==r.follow?r.follow:void 0!==e.follow?e.follow:20,this.compress=void 0!==r.compress?r.compress:void 0===e.compress||e.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent}get method(){return this[I].method}get url(){return M(this[I].parsedURL)}get headers(){return this[I].headers}get redirect(){return this[I].redirect}get signal(){return this[I].signal}clone(){return new V(this)}}function Z(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}w.mixIn(V.prototype),Object.defineProperty(V.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(V.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}}),Z.prototype=Object.create(Error.prototype),Z.prototype.constructor=Z,Z.prototype.name="AbortError";const K=i.default.PassThrough,Y=a.default.resolve;function J(e,t){if(!J.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return w.Promise=J.Promise,new J.Promise((function(r,o){const n=new V(e,t),s=function(e){const t=e[I].parsedURL,r=new A(e[I].headers);if(r.has("Accept")||r.set("Accept","*/*"),!t.protocol||!t.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(t.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof i.default.Readable&&!G)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let o=null;if(null==e.body&&/^(POST|PUT)$/i.test(e.method)&&(o="0"),null!=e.body){const t=x(e);"number"==typeof t&&(o=String(t))}o&&r.set("Content-Length",o),r.has("User-Agent")||r.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip,deflate");let n=e.agent;return"function"==typeof n&&(n=n(t)),r.has("Connection")||n||r.set("Connection","close"),Object.assign({},t,{method:e.method,headers:q(r),agent:n})}(n),a=("https:"===s.protocol?l.default:u.default).request,f=n.signal;let d=null;const h=function(){let e=new Z("The user aborted a request.");o(e),n.body&&n.body instanceof i.default.Readable&&n.body.destroy(e),d&&d.body&&d.body.emit("error",e)};if(f&&f.aborted)return void h();const p=function(){h(),g()},y=a(s);let m;function g(){y.abort(),f&&f.removeEventListener("abort",p),clearTimeout(m)}f&&f.addEventListener("abort",p),n.timeout&&y.once("socket",(function(e){m=setTimeout((function(){o(new b(`network timeout at: ${n.url}`,"request-timeout")),g()}),n.timeout)})),y.on("error",(function(e){o(new b(`request to ${n.url} failed, reason: ${e.message}`,"system",e)),g()})),y.on("response",(function(e){clearTimeout(m);const t=function(e){const t=new A;for(const r of Object.keys(e))if(!E.test(r))if(Array.isArray(e[r]))for(const o of e[r])P.test(o)||(void 0===t[L][r]?t[L][r]=[o]:t[L][r].push(o));else P.test(e[r])||(t[L][r]=[e[r]]);return t}(e.headers);if(J.isRedirect(e.statusCode)){const s=t.get("Location"),i=null===s?null:Y(n.url,s);switch(n.redirect){case"error":return o(new b(`uri requested responds with a redirect, redirect mode is set to error: ${n.url}`,"no-redirect")),void g();case"manual":if(null!==i)try{t.set("Location",i)}catch(e){o(e)}break;case"follow":if(null===i)break;if(n.counter>=n.follow)return o(new b(`maximum redirect reached at: ${n.url}`,"max-redirect")),void g();const s={headers:new A(n.headers),follow:n.follow,counter:n.counter+1,agent:n.agent,compress:n.compress,method:n.method,body:n.body,signal:n.signal,timeout:n.timeout,size:n.size};return 303!==e.statusCode&&n.body&&null===x(n)?(o(new b("Cannot follow redirect with body being a readable stream","unsupported-redirect")),void g()):(303!==e.statusCode&&(301!==e.statusCode&&302!==e.statusCode||"POST"!==n.method)||(s.method="GET",s.body=void 0,s.headers.delete("content-length")),r(J(new V(i,s))),void g())}}e.once("end",(function(){f&&f.removeEventListener("abort",p)}));let s=e.pipe(new K);const i={url:n.url,status:e.statusCode,statusText:e.statusMessage,headers:t,size:n.size,timeout:n.timeout,counter:n.counter},u=t.get("Content-Encoding");if(!n.compress||"HEAD"===n.method||null===u||204===e.statusCode||304===e.statusCode)return d=new F(s,i),void r(d);const a={flush:c.default.Z_SYNC_FLUSH,finishFlush:c.default.Z_SYNC_FLUSH};if("gzip"==u||"x-gzip"==u)return s=s.pipe(c.default.createGunzip(a)),d=new F(s,i),void r(d);if("deflate"!=u&&"x-deflate"!=u){if("br"==u&&"function"==typeof c.default.createBrotliDecompress)return s=s.pipe(c.default.createBrotliDecompress()),d=new F(s,i),void r(d);d=new F(s,i),r(d)}else{e.pipe(new K).once("data",(function(e){s=8==(15&e[0])?s.pipe(c.default.createInflate()):s.pipe(c.default.createInflateRaw()),d=new F(s,i),r(d)}))}})),function(e,t){const r=t.body;null===r?e.end():S(r)?r.stream().pipe(e):Buffer.isBuffer(r)?(e.write(r),e.end()):r.pipe(e)}(y,n)}))}J.isRedirect=function(e){return 301===e||302===e||303===e||307===e||308===e},J.Promise=global.Promise,exports.FetchError=b,exports.Headers=A,exports.Request=V,exports.Response=F,exports.default=J;
;