azion
Version:
Azion Packages for Edge Computing.
37 lines (36 loc) • 17.6 kB
JavaScript
import*as ue from"esbuild";import{flow as ce}from"lodash-es";import Be from"webpack";var O=`
/**
* Built with Azion CLI
* For more information, visit: https://www.azion.com/en/documentation/products/cli/
*/
`,q=`
/**
* WARNING: DEVELOPMENT BUILD
*
* This file is a development build and contains additional injected code
* to facilitate the development and debugging process.
*
* IMPORTANT NOTICES:
* - DO NOT use this build in a production environment.
* - The injected code may cause unexpected behaviors in production.
* - Performance of this build is not optimized for production use.
* - This build may include sensitive debugging information.
*
* To generate an optimized and secure production build use 'azion build'.
*
* If you are seeing this message in a production environment, stop immediately
* and replace this file with a proper production build.
*
* For any issues or questions, please refer to the documentation or contact
* the development team.
*/
`;var C=e=>{let t=e;return{applyPolyfills:n=>r=>s=>s.polyfills?X(t.NodePolyfillsPlugin)?(r.plugins=[...r.plugins||[],new t.NodePolyfillsPlugin(n.production),new t.BabelCustomLoaderPlugin(s.preset.metadata.name,["next"])],r):(r.plugins=[...r.plugins||[],t.NodePolyfillsPlugin(n.production)],r):r,applyAzionModule:n=>r=>(r.plugins=[...r.plugins||[],X(t.AzionPolyfillsPlugin)?new t.AzionPolyfillsPlugin(n.production):t.AzionPolyfillsPlugin(n.production)],r)}};function X(e){return"prototype"in e}var w=(e,t)=>(i={})=>i?t==="esbuild"?(e.define={...e.define,...i},e):(e.plugins=[...e.plugins||[],new Be.DefinePlugin(i)],e):e,B=e=>e.production?O:`${O}${q}`,L=e=>t=>t===void 0?e:t(e);var G={bundle:!0,format:"esm",platform:"browser",mainFields:["browser","module","main"],target:"es2022",keepNames:!0,allowOverwrite:!0,loader:{".js":"js"},outdir:"."};import _e from"fs";import je from"path";import Et from"signale";import H from"signale";var K=process.env.CLEAN_OUTPUT_MODE==="true",Q={displayScope:!1,displayBadge:!1,displayDate:!1,displayFilename:!1,displayLabel:!1,displayTimestamp:!1,underlineLabel:!1,underlineMessage:!1,underlinePrefix:!1,underlineSuffix:!1,uppercaseLabel:!1},P=(e={})=>{let t=new H.Signale({...e});return K&&t.config(Q),Object.assign(t,{breakInteractiveChain:()=>console.log()})},d={deployed:{badge:"\u{1F680}",color:"green",label:"forged",logLevel:"info"},option:{badge:"\u{1F4E6}",color:"green",label:"",logLevel:"info"}},g=(e="Azion")=>new H.Signale({interactive:!1,scope:e,types:d});K&&g().config(Q);var J=(e="Azion")=>({...g(e),interactive:{...P({interactive:!0,scope:[e],types:d})},server:{...g(e).scope(e,"Server"),interactive:P({interactive:!0,scope:[e,"Server"],types:d})},runtime:{...g(e).scope(e,"Runtime"),interactive:P({interactive:!0,scope:[e,"Runtime"],types:d})},prebuild:{...g(e).scope(e,"Pre-Build"),interactive:P({interactive:!0,scope:[e,"Pre-Build"],types:d})},build:{...g(e).scope(e,"Build"),interactive:P({interactive:!0,scope:[e,"Build"],types:d})},postbuild:{...g(e).scope(e,"Post-Build"),interactive:P({interactive:!0,scope:[e,"Post-build"],types:d})},manifest:{...g(e).scope(e,"IaC"),interactive:P({interactive:!0,scope:[e,"IaC"],types:d})}}),kt={...J(),globalScope:e=>({...J(e)})};var Z=process.platform==="win32";function Le(e=import.meta.url,t="bundler"){let i=new RegExp(`(.*${t})(.*)`),o=e.match(i),n=o?o[1]:"";if(e.includes("edge-functions")&&t==="bundler"){let r=new RegExp("(.*edge-functions)(.*)"),s=e.match(r);n=s?s[1]:n}return Z&&(n=new URL(n).pathname,n.startsWith("/")&&(n=n.slice(1))),Z||(n=n.replace("file://","")),n}var ee=Le;var h=ee;import ke from"path";var Ae=()=>ke.resolve(h(import.meta.url,"bundler"),"src"),k=`${Ae()}/polyfills/azion`,c={libs:new Map,globals:new Map,alias:new Map,external:new Map([["azion:storage",`${k}/storage/storage.polyfills.js`],["Azion.env",`${k}/env-vars/env-vars.polyfills.js`],["Azion.networkList",`${k}/network-list/network-list.polyfills.js`],["Azion.Storage",`${k}/storage/storage.polyfills.js`]])};var $e=e=>{let t="bundler-azion-modules-polyfills",i=t,o=/^azion:/,n="azion:";return{name:t,setup:r=>{let s=r.initialOptions;e&&(s.external=s.external||[],[...c.external].forEach(([a])=>{s.external=s.external||[],/^[^:]+:/.test(a)&&!s.external.includes(a)&&s.external.push(a)})),e||(s.inject=s.inject||[],c.external&&[...c.external].forEach(([a,l])=>{!/^[^:]+:/.test(a)&&a?.toLowerCase()?.includes(n.replace(":",""))&&(s.inject=s.inject||[],s.inject.push(l))})),r.onResolve({filter:o},async a=>{if(!e&&c.external.has(a.path))return{path:a.path,namespace:i};if(c.external.has(a.path)&&!(Array.isArray(s?.external)&&s.external.includes(a.path)))return{path:a.path,namespace:i}}),r.onLoad({filter:o,namespace:i},async a=>{if(!c.external.has(a.path))return;let l=c.external.get(a.path);if(!l)throw new Error(`Could not resolve module: ${a.path}`);let p=await _e.promises.readFile(l,"utf8"),u=je.dirname(l);return{loader:"js",contents:p,resolveDir:u}})}}},te=$e;var ne=te;import oe from"path";import{fileURLToPath as Te}from"url";var Ie=Te(import.meta.url),Oe=oe.dirname(Ie),Ne=()=>oe.resolve(Oe,"../../","unenv-preset","src"),m=`${Ne()}/polyfills`,A={inject:{__dirname:`${m}/node/globals/path-dirname.js`,__filename:`${m}/node/globals/path-filename.js`,process:`${m}/node/globals/process.cjs`,performance:"unenv/polyfill/performance",setInterval:`${m}/node/globals/set-interval.js`,clearInterval:`${m}/node/globals/clear-interval.js`},alias:{"azion/utils":"azion/utils","azion/utils/edge":"azion/utils/edge","azion/utils/node":"azion/utils/node","@fastly/http-compute-js":"@fastly/http-compute-js",accepts:"accepts",assert:"assert-browserify",https:`${m}/node/https.js`,module:`${m}/node/module.js`,string_decoder:"string_decoder/lib/string_decoder.js",timers:"timers-browserify/",util:`${m}/node/util.js`},external:["node:async_hooks","node:fs/promises","node:stream","node:crypto"],polyfill:["aziondev:async_hooks:/async-hooks/async-hooks.polyfills.js","aziondev:fs:/fs/fs.polyfills.js","aziondev:fs/promises:/fs/promises/promises.polyfills.js","aziondev:stream:/stream/stream.polyfills.js","aziondev:crypto:/crypto/crypto.polyfills.js","azionprd:fs:/fs.js"]};import y from"fs";import{createRequire as De}from"module";import{builtinModules as ze}from"node:module";import f from"path";import{defineEnv as Me}from"unenv";import Se from"path";var Re=(e,t)=>`${Se.join(h(import.meta.url,"bundler"),e)}${t?`${t}`:""}`,ie={getAbsolutePath:Re};var S=De(import.meta.url),{env:We}=Me({nodeCompat:!0,resolve:!1,overrides:{...A}}),{alias:N,inject:re,polyfill:R,external:se}=We;function Fe(e){if(typeof e=="string")return{importStatement:`import globalVar from "${e}";`,exportName:"globalVar"};if(Array.isArray(e)&&e.length===2){let[t,i]=e;return{importStatement:`import { ${i} } from "${t}";`,exportName:i}}throw new Error(`Invalid global inject value: ${e}`)}function Ue(e){let t="imported-unenv-alias",i={};Object.entries(N).forEach(([n,r])=>{try{let s=r.startsWith("unenv/"),a=S.resolve(r);i[n]=s?a.replace(/\.cjs$/,".mjs"):a.replace(/\.cjs$/,".js")}catch(s){s instanceof Error&&console.log(s.message)}});let o=new RegExp(`^(${Object.keys(i).join("|")})$`);e.onResolve({filter:o},n=>({path:n.path,namespace:t})),e.onLoad({filter:/.*/,namespace:t},async n=>{let r=i[n.path],s=await y.promises.readFile(r,"utf8"),a=f.dirname(r);return{loader:"js",contents:s,resolveDir:a}})}function Ve(e,t,i,o,n,r){let s="node-built-in-modules",a=new RegExp(`^(node:)?(${ze.join("|")})$`);e.onResolve({filter:a},l=>{let p=l.path.replace("node:",""),u=N[p]??N[l.path]??l.path,j=($,T)=>R.find(b=>b.startsWith(`${$}${T}`)),U=($,T,b)=>{let V=se.find(I=>I===b||I===l.path||`node:${b}`===I),Y=j($,b);if(!Y&&V)return{path:l.path.startsWith("node:")?l.path:`node:${l.path}`,external:V.includes(l.path)};if(Y)return{path:b,namespace:T}};return(t?U(i,n,p):U(o,r,p))??{path:u,namespace:s,external:se.includes(l.path)}}),e.onLoad({filter:/.*/,namespace:s},async l=>{let p=S.resolve(l.path),u=await y.promises.readFile(p,"utf8"),j=f.dirname(p);return{loader:"js",contents:u,resolveDir:j}})}function Ye(e,t){let i=/_global_polyfill-([^.]+)\.js$/,o=f.resolve(t("../"),"_global_polyfill-");e.initialOptions.inject=[...e.initialOptions.inject??[],...Object.keys(re).map(n=>`${o}${n}.js`)],e.onResolve({filter:i},n=>({path:n.path})),e.onLoad({filter:i},n=>{let r=n.path.match(i);if(!r?.[1])throw new Error(`Invalid global name: ${n.path}`);let s=r[1],{importStatement:a,exportName:l}=Fe(re[s]);return{contents:`
${a}
globalThis.${s} = ${l};
`}})}function qe(e,t,i,o){e.onLoad({filter:/.*/,namespace:t},async n=>{try{let r=n.path.replace("node:",""),s=R.find(u=>u.startsWith(`${i}${r}`));if(!s)throw new Error(`Polyfill not found for ${r}`);let a=f.join(o,s.replace(`${i}${r}:/`,"")),l=await y.promises.readFile(a,"utf8"),p=f.dirname(a);return{loader:"js",contents:l,resolveDir:p}}catch(r){console.error(`Error loading polyfill for ${n.path}`,r)}})}function Xe(e,t,i,o){e.onLoad({filter:/.*/,namespace:t},async n=>{try{let r=R.find(u=>u.startsWith(`${i}${n.path}`));if(!r)throw new Error(`Polyfill not found for ${n.path}`);let s=f.join(o,r.replace(`${i}${n.path}:/`,"")),a=S.resolve(s),l=await y.promises.readFile(a,"utf8"),p=f.dirname(a);return{loader:"js",contents:l,resolveDir:p}}catch(r){console.error(`Error loading polyfill prod for ${n.path}`,r)}})}function Ge(e){if(y.existsSync(f.join(process.cwd(),".next"))){let t=y.readFileSync(f.join(process.cwd(),".next/BUILD_ID"),"utf-8");e.define={...e.define,"process.env.NEXT_RUNTIME":e.define?.["process.env.NEXT_RUNTIME"]||'"edge"',"process.env.NEXT_COMPUTE_JS":"true","process.env.__NEXT_BUILD_ID":`"${t}"`}}}var Je=e=>{let t="bundler-node-modules-polyfills",i="internal-env-dev",o="internal-env-prod",n="/polyfills",r="/polyfills/node",s="aziondev:",a="azionprd:",l=(p,u)=>ie.getAbsolutePath(p,u);return{name:t,setup:p=>{let u=p.initialOptions;u.define=u.define||{},u.define?.global||(u.define.global="globalThis"),u.define={...u.define,"process.env.NODE_ENV":'"production"'},Ge(u),u.inject=u.inject||[],u.alias={...u.alias},Ve(p,e,a,s,o,i),Ue(p),Ye(p,l),qe(p,i,s,l("src",n)),Xe(p,o,a,l("../unenv-preset/src",r))}}},ae=Je;var le=ae;var pe=C({NodePolyfillsPlugin:le,AzionPolyfillsPlugin:ne}),He=(e,t)=>i=>(i&&(e.banner=e.banner||{},e.banner.js=e.banner.js?`${e.banner.js} ${i}`:i,t.production&&(e.banner.js+=`
// This file is generated by Azion. Do not edit it manually.
// Dynamic require is not supported in production mode.
import { createRequire as _createRequire } from "node:module";
const require = _createRequire(import.meta.url);`)),e),Ke=(e,t)=>{let i=e.baseOutputDir;return{baseConfig:{...G,entryPoints:typeof e.entry=="string"?[e.entry]:e.entry,...i?{outdir:i}:{},entryNames:"[dir]/[name]",minify:t.production,plugins:[],banner:{js:B(t)}},mergeConfig:n=>ce([()=>pe.applyPolyfills(t)(n)(e),()=>pe.applyAzionModule(t)(n),()=>He(n,t)(e?.setup?.contentToInject),()=>w(n,"esbuild")(e?.setup?.defineVars),()=>L(n)(e.extend)])(n),applyConfig:n=>n,executeBuild:fe}},fe=async e=>{let t=ce([()=>e.mergeConfig(e.baseConfig),()=>e.applyConfig(e.baseConfig)])(e.baseConfig);await ue.build(t)};import{flow as Ce}from"lodash-es";import v from"webpack";import{readFileSync as Qe}from"fs";function D(e){try{return e.map(t=>Qe(t,"utf-8")).join(`
`)}catch(t){throw new Error(`Failed to generate webpack banner: ${t instanceof Error?t.message:String(t)}`)}}var z=class{buildProd;prefix;constructor(t){this.buildProd=t,this.prefix="azion:"}apply(t){t.options.plugins?.length||(t.options.plugins=[]),t.options.plugins.push(new t.webpack.NormalModuleReplacementPlugin(new RegExp(`^${this.prefix}`),o=>{let n=o.request.replace(new RegExp(`^${this.prefix}`),"");o.request=n}));let i=new Map([...c.external].filter(([o])=>new RegExp(`^${this.prefix}`).test(o)));this.buildProd||[...c.external].forEach(([o])=>{if(!/^[^:]+:/.test(o)&&o?.toLowerCase()?.includes(this.prefix.replace(":",""))){let r=c.external.get(o);if(!r)throw new Error(`Banner content not found for key: ${o}`);t.options.plugins?.push(new t.webpack.BannerPlugin({banner:D([r]),raw:!0}))}}),this.buildProd?t.options.externals={...Object.fromEntries([...i].flatMap(([o])=>[[o,o],[`${this.prefix}${o}`,`${this.prefix}${o}`]])),...typeof t.options.externals=="object"?t.options.externals:{}}:(t.options.plugins?.push(new t.webpack.NormalModuleReplacementPlugin(new RegExp(`^${this.prefix}`),o=>{let n=o.request.replace(new RegExp(`^${this.prefix}`),"");o.request=n})),t.options.resolve=t.options.resolve||{},t.options.resolve.fallback={...Object.fromEntries([...i].map(([o,n])=>[o.replace(new RegExp(`^${this.prefix}`),""),n])),...t.options.resolve.fallback})}},de=z;var ge=de;import{createRequire as Ze}from"module";var x=Ze(import.meta.url),M=class{preset;presetsAllowed;constructor(t,i){this.preset=t||"",this.presetsAllowed=i||[]}apply(t){let i=t.options.module.rules||[];this.presetsAllowed.includes(this.preset)&&i.push({test:/\.func.m?js$/,exclude:/node_modules/,use:{loader:x.resolve("babel-loader"),options:{compact:!1,plugins:[[x.resolve("@babel/plugin-proposal-optional-chaining-assign"),{version:"2023-07"}]]}}}),i.push({test:/\.ts$/,exclude:/node_modules/,use:{loader:x.resolve("babel-loader"),options:{compact:!1,presets:[[x.resolve("@babel/preset-env"),{targets:{node:"current"}}],x.resolve("@babel/preset-typescript")]}}}),t.options.module.rules=i}},me=M;var Pe=me;import he from"fs";import{createRequire as et}from"module";import _ from"path";import{defineEnv as tt}from"unenv";var W=et(import.meta.url),{env:nt}=tt({nodeCompat:!0,resolve:!1,overrides:{...A}}),{alias:be,inject:ot,polyfill:it,external:rt}=nt,F=class e{INTERNAL_POLYFILL_PATH="/polyfills";INTERNAL_POLYFILL_PATH_PROD="/polyfills/node";POLYFILL_PREFIX_DEV="aziondev:";POLYFILL_PREFIX_PROD="azionprd:";isProduction;prefix;constructor(t){this.isProduction=t,this.prefix="node:"}static getAbsolutePath=(t,i)=>`${_.join(h(import.meta.url,"bundler"),i)}${t}`;changeToPolyfillPath=(t,i,o,n)=>{let r=t.replace(new RegExp(`^${this.prefix}`),""),s=it.find(a=>a.startsWith(`${o}${r}`));if(s){let[,,a]=s.split(":"),l=_.join(n,a),p=W.resolve(l);return[t,p]}return[t,W.resolve(i)]};apply(t){t.options.plugins?.length||(t.options.plugins=[]),t.options.plugins.push(new t.webpack.NormalModuleReplacementPlugin(new RegExp(`^${this.prefix}`),o=>{let n=o.request.replace(new RegExp(`^${this.prefix}`),"");o.request=n})),t.options.plugins.push(new t.webpack.ProvidePlugin(Object.fromEntries(Object.entries(ot).map(([o,n])=>typeof n=="string"?[o,W.resolve(n)]:[o,n]))));let i={NODE_ENV:"production"};if(he.existsSync(_.join(process.cwd(),".next"))){let o=he.readFileSync(_.join(process.cwd(),".next/BUILD_ID"),"utf-8");i.NEXT_RUNTIME="edge",i.NEXT_COMPUTE_JS=!0,i.__NEXT_BUILD_ID=o}t.options.plugins.push(new t.webpack.EnvironmentPlugin(i)),this.isProduction&&(t.options.externals={...typeof t.options.externals=="object"?t.options.externals:{},...Object.fromEntries([...rt].flatMap(o=>{let n=o.replace(new RegExp(`^${this.prefix}`),"");return[[o,o],[n,n]]}))}),t.options.resolve.alias={...t.options.resolve.alias,...be},t.options.resolve.fallback={...t.options.resolve.fallback,...be},this.isProduction?(t.options.resolve.alias={...Object.fromEntries(Object.entries(t.options.resolve.alias).map(([o,n])=>this.changeToPolyfillPath(o,n,this.POLYFILL_PREFIX_PROD,e.getAbsolutePath(this.INTERNAL_POLYFILL_PATH_PROD,"../unenv-preset/src"))))},t.options.resolve.fallback={...Object.fromEntries(Object.entries(t.options.resolve.fallback).map(([o,n])=>this.changeToPolyfillPath(o,n,this.POLYFILL_PREFIX_PROD,e.getAbsolutePath(this.INTERNAL_POLYFILL_PATH_PROD,"../unenv-preset/src"))))}):(t.options.resolve.alias={...Object.fromEntries(Object.entries(t.options.resolve.alias).map(([o,n])=>this.changeToPolyfillPath(o,n,this.POLYFILL_PREFIX_DEV,e.getAbsolutePath(this.INTERNAL_POLYFILL_PATH,"src"))))},t.options.resolve.fallback={...Object.fromEntries(Object.entries(t.options.resolve.fallback).map(([o,n])=>this.changeToPolyfillPath(o,n,this.POLYFILL_PREFIX_DEV,e.getAbsolutePath(this.INTERNAL_POLYFILL_PATH,"src"))))})}},ye=F;var xe=ye;import Ee from"webpack";var st={experiments:{outputModule:!0},resolve:{extensions:[".tsx",".ts",".js"],mainFields:["browser","module","main"]},mode:"production",target:["webworker","es2022"],plugins:[new Ee.ProgressPlugin,new Ee.optimize.LimitChunkCountPlugin({maxChunks:1})]},E=st;var ve=C({NodePolyfillsPlugin:xe,AzionPolyfillsPlugin:ge,BabelCustomLoaderPlugin:Pe}),at=e=>t=>{if(!t)return e;let i=e.plugins?.findIndex(o=>o instanceof v.BannerPlugin)??-1;if(i!==-1&&e.plugins){let o=e.plugins[i].options.banner;e.plugins=e.plugins.filter((n,r)=>r!==i),e.plugins.push(new v.BannerPlugin({banner:`${o} ${t}`,raw:!0}))}else e.plugins=[...e.plugins||[],new v.BannerPlugin({banner:t,raw:!0})];return e},lt=(e,t)=>{let i=e.baseOutputDir||process.cwd(),o=E.plugins||[];return{baseConfig:{...E,entry:e.entry,output:{...E.output,path:i,filename:"[name]",globalObject:"globalThis"},plugins:[...o.filter(r=>!!r),new v.BannerPlugin({banner:B(t),raw:!0,entryOnly:!0})],optimization:{...E.optimization,minimize:t.production}},mergeConfig:r=>Ce([()=>ve.applyPolyfills(t)(r)(e),()=>ve.applyAzionModule(t)(r),()=>at(r)(e?.setup?.contentToInject),()=>w(r,"webpack")(e?.setup?.defineVars),()=>L(r)(e.extend)])(r),applyConfig:r=>r,executeBuild:we}},we=async e=>{await new Promise((t,i)=>{let o=Ce([()=>e.mergeConfig(e.baseConfig)])(e.baseConfig);v(o,(n,r)=>{if(n||r?.hasErrors()){let a=r?.toJson()?.errors?.map(l=>l.message).join(`
`);console.log(n),i(new Error(a));return}t()})})};export{Ke as createAzionESBuildConfig,lt as createAzionWebpackConfig,fe as executeESBuildBuild,we as executeWebpackBuild};