import{dirname,join,relative,sep}from"node:path";import{mkdir,readFile,readdir,writeFile}from"node:fs/promises";import{performance}from"node:perf_hooks";import{gzipSync}from"node:zlib";const APPLICATION_BUILD_PROFILE_SCHEMA_VERSION=1;function roundDuration(e){return Math.round(Math.max(0,e)*10)/10}function createMutableOutputSize(){return{files:0,gzipBytes:0,rawBytes:0}}function toOutputSize(e){return{files:e.files,gzipBytes:e.gzipBytes,rawBytes:e.rawBytes}}function toProfilePath(e,t){return relative(e,t).split(sep).join(`/`)}function measureFileSize(e){return{gzipBytes:gzipSync(e).byteLength,rawBytes:e.byteLength}}function addFileSize(e,t){e.files+=1,e.rawBytes+=t.rawBytes,e.gzipBytes+=t.gzipBytes}var ApplicationBuildProfiler=class{#e;#t=[];#n;#r=!1;constructor(e={}){this.#e=e.now??performance.now.bind(performance),this.#n=this.#e()}async measure(e,t){if(this.#r)throw Error(`Cannot record a phase after the build profile has finished.`);let n=this.#e();try{return await t()}finally{this.#t.push({durationMs:roundDuration(this.#e()-n),name:e})}}finish(){if(this.#r)throw Error(`The build profile has already finished.`);return this.#r=!0,{durationMs:roundDuration(this.#e()-this.#n),phases:[...this.#t]}}};function createApplicationBuildProfile(e){return{durationMs:e.timing.durationMs,kind:`eve-build-profile`,output:e.output,phases:e.timing.phases,schemaVersion:1,target:e.target}}async function measureApplicationBuildOutput(e){let n=createMutableOutputSize(),r=new Map,visit=async(i,o)=>{let s=await readdir(i,{withFileTypes:!0});for(let a of s){let s=join(i,a.name);if(a.isDirectory()){await visit(s,a.name.endsWith(`.func`)?toProfilePath(e,s):o);continue}if(!a.isFile())continue;let c=measureFileSize(await readFile(s));if(addFileSize(n,c),o!==void 0){let e=r.get(o)??createMutableOutputSize();addFileSize(e,c),r.set(o,e)}}};return await visit(e,void 0),{...toOutputSize(n),functionBundles:[...r.entries()].map(([e,t])=>({path:e,...toOutputSize(t)})).sort((e,t)=>e.path.localeCompare(t.path))}}async function writeApplicationBuildProfile(t,n){await mkdir(dirname(t),{recursive:!0}),await writeFile(t,`${JSON.stringify(n,null,2)}\n`,`utf8`)}export{APPLICATION_BUILD_PROFILE_SCHEMA_VERSION,ApplicationBuildProfiler,createApplicationBuildProfile,measureApplicationBuildOutput,writeApplicationBuildProfile};